结构的前向声明无效

invalid forward declaration of struct

本文关键字:声明 无效 结构      更新时间:2023-10-16

-编辑--很抱歉,我把人们弄糊涂了,我只是快速地键入了这段代码,而不是复制和粘贴,所以我实际上在代码中定义了#ifndef 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
*/

有人告诉我,在头文件中向前声明另一个类,然后将另一个文件包括在cpp文件中是可行的,但在标记的行中,我得到了一个错误,只说"向前声明‘struct b’"

有人能告诉我我做错了什么吗?

包括一个标头,比如说a.h中的b.h。不要在a.h中转发声明b。b.h可以保持原样。

否则你会得到类似的东西

class B {};
....
class B;

只对这样的错误进行预处理总是明智的。