--编辑--
很抱歉让人们感到困惑,我只是快速输入这段代码而不是复制和粘贴,所以我实际上在我的代码中执行了#ifndef A_H #define A_H。我更改了下面的代码以表明
-- 结束编辑--
我有两个类,每个类都包含一个指向另一个类实例的指针,但这给我带来了问题。我的代码类似于下面的
// A.h
#ifndef A_H
#define A_H
class B; // compiler error here
class A
{
B* foo;
// other members and functions
};
#endif
// A.cpp
#include "A.h"
#include "B.h"
/*
declare functions and use methods in both A and B
*/
// B.h
#ifndef B_H
#define B_H
class A;
class B
{
A** bar;
// other stuff
};
#endif
//B.cpp
#include "A.h"
#include "B.h"
/*
declare functions and use methods in both A and B
*/
我被告知在头文件中前向声明另一个类 int 然后将另一个文件包含在 cpp 文件中是可行的,但是在标记的行上我得到一个错误,它只是说“'struct b' 的前向声明”
谁能告诉我我做错了什么?
最佳答案
包含一个标题,比如在 a.h 中说 b.h。不要在 a.h 中转发声明 B。 b.h 可以保持原样。
否则你会得到这样的东西
class B {};
....
class B;
只对此类错误进行预处理总是明智的。
关于c++ - 结构的无效前向声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12341487/