我有很多类,它们彼此之间非常接近
class A
{
//code
};
class B
{
A* field;
//code
};
class C: public B
{
//code
};
等等。
我想将它们放在单独的 header 中(A.h
、B.h
...),但为了避免将每个 header 添加到项目中,我需要一个像 这样的 header >myLib.h
,这只是一个包含我编写的所有类所需的 header 。我如何实现它?
此外,我认为不要使用 #pragma once;
并使其正常工作
#ifndef _MY_LIB_H
#define _MY_LIB_H
#endif
我应该把它放在哪里?在每个标题中?
我试过这样做
class A;
class B;
...
在myLib.h
但随后将 myLib.h
添加到 main.cpp
不足以在那里使用 A 或 B 对象。此外,在 B.h
中
#inlude myLib.h
void someMethod()
{
//field is instance of A
this.field.otherMethod();
}
导致错误,因为 A 的方法是在 A.h
中声明的,而不是在 myLib.h
中声明的。
抱歉,这个问题又长又乱。
最佳答案
您应该在A.h
、B.h
、C.h
中使用单独的包含防护:
// Note: not a good name for a guard macro (too short)
#ifndef _A_H
#define _A_H
// definition of A
#endif
然后 MyLib.h
变得简单:
#include<A.h>
#include<B.h>
#include<C.h>
当然,您的每个 header 都应根据需要手动包含尽可能多的其他 header ,以便它可以独立存在(例如 C.h
需要包含 B.h
以便如果有人直接包含 C.h
,代码就会编译)。
在某些情况下,您不需要让一个 header 包含另一个 header ,因为前向声明就足够了——例如在 B.h
中,其中声明了一个 A*
成员:
#ifndef _B_H
#define _B_H
class A;
class B
{
A* field;
};
#endif
关于c++ - 使包含多个类需要一个 header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11358271/