您好,我已经阅读过有关此主题的类似问题,但我无法解决我的问题。我想我必须做一个前瞻性声明,所以我尝试了以下操作。
我有三个类 A、B 和 InterfaceA
定义接口A
#ifndef INTERFACE_A_H
#define INTERFACE_A_H
#include "B.h"
namespace Example
{
class B; // Forward declaration?
class InterfaceA
{
Example::B test;
};
}
#endif
Run Code Online (Sandbox Code Playgroud)
定义A类
#ifndef A_H
#define A_H
#include "InterfaceA.h"
namespace Example
{
class A : public Example::InterfaceA
{
};
}
#endif
Run Code Online (Sandbox Code Playgroud)
定义B类
#ifndef B_H
#define B_H
#include "A.h"
namespace Example
{
class A; // Forward declaration?
class B
{
Example::A test;
};
}
#endif
Run Code Online (Sandbox Code Playgroud)
主要的
#include "A.h"
#include "B.h"
int main()
{
Example::A a;
Example::B b;
}
Run Code Online (Sandbox Code Playgroud)
我在 Visual Studio 中收到以下错误:
'Example::B::test' 使用未定义的类 'Example::A'
编辑:到目前为止,感谢您提供的所有帮助。这非常有帮助。我认为我的问题是我在实际项目中的设计非常糟糕。我会改变这一点。
除此之外,我现在对前向声明有了更好的理解:-)
如果您确实需要 A 类引用 B 类,反之亦然,请考虑使用指针,而不是将 A 和 B 的实例作为数据成员,例如:
// A.h
#pragma once
#include <memory> // for std::unique_ptr
// Forward declaration (A references B using pointer)
class B;
class A
{
...
std::unique_ptr<B> m_pB;
};
Run Code Online (Sandbox Code Playgroud)
同样:
// B.h
#pragma once
#include <memory> // for std::unique_ptr
// Forward declaration (B references A using pointer)
class A
class B
{
...
std::unique_ptr<A> m_pA;
};
Run Code Online (Sandbox Code Playgroud)
PS
与您问题的核心无关,但请注意,我使用的#pragma once不是“旧式”,#ifndef/#define/#endif包括警卫;#pragma once对我来说似乎更简单、更清晰。