6

それを友達として使用しているクラスに「Class1.h」を#includeする必要があるかどうか疑問に思っていました。たとえば、Class1 クラスに権限を付与するクラスの .h ファイル。

class Class2 {
   friend class Class1;
}

#include "Class1.h" が必要ですか、それとも不要ですか? また、Class2 クラスでは、Class1 オブジェクトが作成または使用されることはありません。Class1 は Class2 を操作するだけで、その逆はありません。

4

2 に答える 2

11

The syntax is:

friend class Class1;

And no, you don't include the header.

More generally, you don't need to include the header unless you are actually making use of the class definition in some way (e.g. you use an instance of the class and the compiler needs to know what's in it). If you're just referring to the class by name, e.g. you only have a pointer to an instance of the class and you're passing it around, then the compiler doesn't need to see the class definition - it suffices to tell it about the class by declaring it:

class Class1;

This is important for two reasons: the minor one is that it allows you to define types which refer to each other (but you shouldn't!); the major one is that it allows you to reduce the physical coupling in your code base, which can help reduce compile times.


To answer Gary's comment, observe that this compiles and links fine:

class X;

class Y
{
    X *x;
};

int main()
{
    Y y;
    return 0;
}

There is no need to provide the definition of X unless you actually use something from X.

于 2012-04-11T20:25:09.147 に答える