编辑:对于将来发现此问题的任何人,以下阅读对我有很大帮助:http://www.umich.edu/~eecs381/handouts/IncompleteDeclarations.pdf
我有一个类,它的头文件看起来大致像
#ifndef FOO_HPP_
#define FOO_HPP_
#include <memory>
#include "Bar.hpp"
using namespace std;
class Foo {
shared_ptr<Bar> bar;
//other members omitted
};
#endif /* FOO_HPP_ */
我收到编译时错误:模板 1 无效(对于 bar 成员)。
Bar.hpp 看起来大概像这样:
#ifndef BAR_HPP_
#define BAR_HPP_
#include "Foo.hpp"
using namespace std;
class Bar {
//private and protected member omitted
public:
//other public members omitted
virtual int collide(bool p, Foo& f) = 0;
};
#endif /* BAR_HPP_ */
如果我现在用 class Bar;
替换 "Foo.hpp"中的 #include "Bar.hpp"
,CDT 将在其下划线并显示错误:前向声明“类(class)酒吧”的
我该如何解决这个问题?
最佳答案
这个问题是因为 bar.hpp 正在使用 foo.hpp 而 foo.hpp 正在使用 bar.hpp
要解决此问题,请将其写入 foo.hpp 并删除 bar.hpp 引用:
#ifndef FOO_HPP_
#define FOO_HPP_
#include <memory>
using namespace std;
class Bar; //<====== add this
class Foo {
shared_ptr<Bar> bar;
//other members omitted
void DoWork(); //<===== Function that does stuff to bar
};
#endif /* FOO_HPP_ */
在 Foo.cpp 中
#include "Foo.hpp"
#include "Bar.hpp"
void Foo::DoWork()
{
bar.Func();
}
在 bar.hpp 中:
#ifndef BAR_HPP_
#define BAR_HPP_
using namespace std;
class Foo; //<====== add this
class Bar {
//private and protected member omitted
public:
//other public members omitted
void Func()
{
while(true); //Hang for debug
};
virtual int collide(bool p, Foo& f) = 0;
};
只要您使用引用类型(Foo* 或 Foo& 而不是直接使用 Foo),这将导致链接时间原型(prototype)解析,这应该适合您。
关于c++ - 循环类依赖 : Forward declaration error vs. #include 错误 ("template argument invalid"),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29135338/