【问题标题】:invalid forward declaration of struct结构的无效前向声明
【发布时间】:2012-09-09 17:56:42
【问题描述】:

--编辑-- 很抱歉让人们感到困惑,我只是快速输入这段代码而不是复制和粘贴,所以我实际上在我的代码中执行#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
*/

有人告诉我,在头文件中前向声明另一个类,然后在 cpp 文件中包含另一个文件会起作用,但是在标记的行上我收到一个错误,只是说“前向声明 'struct b'”

谁能告诉我我做错了什么?

【问题讨论】:

  • 我会大胆猜测您的包含守卫会弄乱类名。
  • 同意,#define blah \n class blah 将被替换为 class [nothing here]
  • @Raphael 我建议你阅读一些真实的 POSIX 源代码。他们总是使用#ifndef __FILENAME_H__ 等。
  • @H2CO3,真的吗?这很糟糕(至少对于非实现代码而言)。我同意它背后的逻辑,但stackoverflow.com/questions/228783/…。我总是使用FILENAME_H
  • @OP,包括注释掉了,代码works on GCC 4.7.1

标签: c++ forward-declaration


【解决方案1】:

包括一个标题,让 b.h 在 a.h 中。不要在 a.h 中转发声明 B。 b.h 可以保持原样。

否则你会得到喜欢的东西

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

只对此类错误进行预处理总是明智的。

【讨论】:

    猜你喜欢
    • 2012-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-06
    • 2017-04-05
    • 2016-07-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多