尽管提供了功能体,但仍期待功能体

Expecting function body despite it being provided

我有一个名为 Node 的基 class,它定义了两个函数:indenttoString。前者将被所有派生的 classes 使用而不被覆盖,但是后者将在派生的 classes 中被覆盖。

Node.hpp

#ifndef NODE_H
#define NODE_H

#include <string>
#include <vector>
#include <memory>

class Node {
    public:
        virtual std::string toString(int level) const {};
        std::string indent(int level);
};

#endif

Node.cpp

#include "Node.hpp"

std::string Node::indent(int level) {
    std::string indt;
    for(int i = 0; i < level; i++) {
        indt += "\t";
    }
    return indt;
}

我有一个派生的 class FunctionNode 想要覆盖 node.hpp.

中的 toString

函数Node.hpp

#ifndef FUNCTION_NODE_H
#define FUNCTION_NODE_H

#include "TypeNode.hpp"
#include "ParamsNode.hpp"
#include "BlockNode.hpp"
#include "DeclarationNode.hpp"

class FunctionNode : public DeclarationNode {
    std::shared_ptr<TypeNode> type;
    std::string name;
    std::shared_ptr<ParamsNode> paramList;
    std::shared_ptr<BlockNode> block;

    public:
        FunctionNode(std::shared_ptr<TypeNode> type,
                const std::string &name,
                std::shared_ptr<ParamsNode> paramList,
                std::shared_ptr<BlockNode> block)
            : type(std::move(type)), name(name),
                paramList(std::move(paramList)), block(std::move(block)) {}
};

#endif

请注意,DeclarationNode 派生自 Node

函数Node.cpp

#include "FunctionNode.hpp"

std::string FunctionNode::toString(int level) const override {
    std::string indt = indent(level);
    std::string s = indt + "FunctionNode\n"; 
    s += type->toString(level + 1);
    s += indt + "\t" + name + "\n";
    s += paramList->toString(level + 1);
    s += block->toString(level + 1);
    return s;
}

当我尝试使用 Makefile 中的以下行将 FunctionNode.cpp 编译为对象时。

FunctionNode.o: FunctionNode.cpp FunctionNode.hpp TypeNode.hpp ParamsNode.hpp BlockNode.hpp

我收到以下错误。

FunctionNode.cpp:3:55: error: expected function body after function declarator
std::string FunctionNode::toString(int level) const override {
                                                      ^

但是我提供了函数体。我该如何解决这个错误?

您的程序没有 return 方法语句 Node::toString。除此之外似乎没有任何其他错误,除了

fatal error: TypeNode.hpp: No such file or directory

因为您没有在原始问题中提供 TypeNode.hpp

程序没有你提到的错误可以看出here. If you can provide a minimal reproducible example并编辑你的问题,这会很好。注意FunctionNode::toString在上面link.

中的FunctionNodeclass里面也声明了

要覆盖子 class 中的函数,您需要在 class 定义中编写声明。覆盖说明符只会出现在头文件中。

头文件

class FunctionNode : public DeclarationNode {
  FunctionNode(...) { ... }
  std::string toString(int level) const override; 
};

源文件

#include "FunctionNode.hpp"

std::string FunctionNode::toString(int level) const {
  ...
}