首页 > 解决方案 > 构造函数后导致这些“意外标记”错误的原因是什么?

问题描述

我正在研究电路模拟器/寻路系统,但我不断收到这些奇怪的编译错误。我对OO C++还没有那么丰富的经验来弄清楚自己......

对象树

我项目中的对象是这样实现的:

我的Object类是我项目中所有内容的基类,通过为所有内容提供名称和 id 来进行调试非常有用。我要求每个组件都需要一个电路来使用(将其视为组件的父级)。我通过在 Component 类中创建一个需要引用 Circuit 对象的构造函数来实现这一点。

起初,一切工作和编译都很好,但是当我引入 Circuit 类并在 Component 中添加带有 Circuit 参考参数的构造函数时,一切都出错了......

编译错误

现在我不断收到这些看似随机的语法和缺少标记的错误。(Intellisense 不标记它们?)

弹出的前四个错误是:

C2238: unexpected token(s) preceding ';'.

在 Component.hpp 的第 10 行。在文件 Circuit.hpp 的第 12 行。两者都在构造函数定义之后。(见下面的代码)

接下来的四个错误指向相同的位置,但它指出:

C2143: syntax error: missing ';' before '*'.

然后,又出现了 30 个错误,但我认为它们是这些错误的结果,可以肯定的是,它们是:

(大声笑,无法嵌入图像,由于没有足够的声誉,所以一个链接代替......)

点击这里查看错误

我试过的

我尝试了以下方法:

怎么修?

这个令人沮丧的问题阻止了我在这个项目上进一步工作,是什么原因造成的,我该如何解决?我会很高兴知道。

对象.hpp

#pragma once
#include <string>

using std::string;

class Object
{
public:
    Object();
    Object(string name);
    string name;
    const int id;
    virtual string toString();
private:
    static int currentId;
};

对象.cpp

#include "Object.hpp"

int Object::currentId = 0;

Object::Object() : id(++Object::currentId), name("Object")
{ }

Object::Object(string name) : id(++Object::currentId), name(name)
{ }

string Object::toString()
{
    return name + "#" + std::to_string(id);
}

组件.hpp

#pragma once
#include "Object.hpp"
#include "Circuit.hpp"

class Component : public Object
{
public:
    Component(std::string name, Circuit* container);
    Circuit *container; // <- Error points to the beginning of this line
};

组件.cpp

#include "Component.hpp"

Component::Component(string name, Circuit* container) : Object(name), container(container)
{ }

开关.hpp

#pragma once
#include "Component.hpp"
#include "Wire.hpp"

class Switch : public Component
{
public:
    Switch(string name, Circuit* container, Wire& wire1, Wire& wire2);
    Wire* wire1;
    Wire* wire2;
    void setEnabled(bool enabled);
    bool getEnabled();

private:
    bool enabled;
};

开关.cpp

Switch::Switch(string name, Circuit* container, Wire& wire1, Wire& wire2) : Component(name + "-Switch", container), wire1(&wire1), wire2(&wire2), enabled(false)
{ }

...

电路.hpp

#pragma once
#include "Object.hpp"
#include "Wire.hpp"

class Circuit : public Object
{
public:
    Circuit(std::string name);
    Wire* powerWire; // <- Error points to the beginning of this line
    bool isPowered(Wire& wire);
    bool getActive();
    void setActive(bool active);
private:
    bool active;
};

电路.cpp

#include "Circuit.hpp"
#include "Util.hpp"

Circuit::Circuit(string name) : Object(name + "-Circuit")
{
    active = false;
    powerWire = new Wire(name + "-PowerWire", this);
}

...

标签: c++inheritance

解决方案


您还没有显示Wire.hpp,但我的猜测是它包含Component.hpp,这为您提供了标题包含的循环(因为Component.hpp包含Circuit.hppCircuit.hpp包含Wire.hpp)。

您将不得不用前向声明替换其中一些包含项以打破循环。


推荐阅读