0

我有很多课程,它们彼此非常接近,例如

class A
{
//code
};

class B
{
   A* field;
//code
};

class C: public B
{
//code
};

等等。而且我想将它们放在单独的标题中(A.hB.h...),但为了避免将每个标题添加到项目中,我需要一个类似的标题myLib.h,这只是一个包含我编写的所有类的标题。我如何实现它?

我也认为不要使用#pragma once;并使其正常工作

#ifndef _MY_LIB_H
#define _MY_LIB_H
#endif

我应该把它放在哪里?在每个标题中?

我试过这样做

class A;
class B;
...

myLib.h

但是添加myLib.hmain.cpp并不足以在那里使用 A 或 B 对象。另外,在B.h

#inlude myLib.h

void someMethod()
{
//field is instance of A
  this.field.otherMethod();
}

导致错误,因为 A 的方法是在 中声明的A.h,而不是在 中myLib.h

对不起,冗长而纠结的问题。

4

2 回答 2

2

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>

当然,您的每个标题都应该根据需要手动包含尽可能多的其他标题,以便它可以独立(例如,如果有人直接包含,则C.h需要包含B.h以便代码编译C.h)。

在某些情况下,您不需要一个标头包含另一个标头,因为前向声明就足够了——例如B.h,在A*声明成员的地方:

#ifndef _B_H
#define _B_H
class A;

class B
{
   A* field;
};
#endif
于 2012-07-06T08:11:13.087 回答
2

除了使用模式

#ifndef _A_H
#define _A_H

   ... Stuffs

#endif

在每个标题中,我总是添加

#ifndef _A_H
#include <A.h>
#endif
#ifndef _B_H
#include <B.h>
#endif
....

到其他标题,例如myLib.h. 这大大提高了编译速度,因为编译器不需要加载和扫描已经扫描过的低级头文件。

I do not add this to my cpp files, because the number of headers in cpp is typically reasonable, while it mich more difficult to track relations between headers.

于 2012-07-06T08:17:56.083 回答