c++ - 循环类依赖 : Forward declaration error vs. #include 错误 ("template argument invalid")

标签 c++ c++11 gcc windows-7 eclipse-cdt

编辑:对于将来发现此问题的任何人,以下阅读对我有很大帮助: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/

相关文章:

c++ - 如何同时处理一个 C++ 类的多个成员?

c++ - 使用统一初始化初始化对象和指针对象不起作用

c++ - 如何显示cmake的gcc版本?

c++ - 没有 cbegin()/cend() 的 std::initializer_list

c - glibc/realloc/无效指针

gcc - SysTick->LOAD 与 SysTick->CALIB

c++ - QHash 迭代器示例 - 运算符 << 不匹配?

c++ - 没有用于调用 Dice::Dice(类构造函数)的匹配函数

java - java真的有指针吗?

c++ - 线程连接问题