C++中在一个类中嵌套的定义另外一个类,嵌套类并不能自动获得外部类的私有成员的访问权限,需要定义嵌套类为外部类的友元。定义如下:
class A{
public:
class B;
friend class B;
friend class B{
void func();
};
};
void A::B::func(){
}
注意,嵌套类的定义必须和友元声明分开,否则会报错:
testFriend.cpp:15:2: error: class definition may not be declared a friend
friend class B{
^
经过测试,将嵌套类的声明与友元声明合并,进行编译:
g++ -o testFriend.o -c testFriend.cpp
也可以通过编译,具体是否还有其他影响有待进一步验证