是什么导致了构造函数之后的这些"意外令牌"错误?



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

对象树

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

  • 对象
    • 组件
      • 线
      • 开关
    • 西鲁伊特

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

起初,一切正常且编译良好,但是当我引入 Circuit 类并在带有 Circuit 引用参数的组件中添加构造函数时,一切都出错了......

编译错误

现在我不断收到这些看似随机的语法和丢失的标记错误。(智能感知不标记它们?

弹出的前四个错误是:

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

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

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

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

然后,又有 30 个错误接踵而至,但我认为它们是这些错误的结果,可以肯定的是,它们是:

(哈哈,无法嵌入图像,这是由于没有足够的声誉造成的,所以一个链接代替......

单击此处查看错误

我尝试了什么

我尝试了以下方法:

  • 使用引用而不是指针。(Circuit* c改为Circuit& c)
  • 删除构造函数初始值设定项列表中的名称字符串连接内容。(... : Object(name + "blah")改为... : Object(name))
  • 将整个Visual Studio项目
  • 重写为一个新的Visual Studio项目。
  • 将构造函数初始值设定项列表放在头文件中。
  • 很多谷歌搜索...而且没有很多解决...

如何解决?

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

对象.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)
{ }

Switch.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);
}
...

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

您必须用前向声明替换其中一些包含物以打破循环。

最新更新