【发布时间】: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。