C++ 如何使一个文件中的非成员函数与另一个文件中的类成为好友?
假设我有一个文件 //X.h(第一个文件) 我的问题是: 如何使main.cpp中的Y类成为X的朋友 我正在考虑将类Y分解成.h和.cpp文件,并将Y.h文件包含到X.h中,然后从那里开始。还有别的办法吗。我的意思是在代码的当前条件下,让Y成为X的朋友: 我在当前条件下遇到的错误是:C++ 如何使一个文件中的非成员函数与另一个文件中的类成为好友?,c++,friend,C++,Friend,假设我有一个文件 //X.h(第一个文件) 我的问题是: 如何使main.cpp中的Y类成为X的朋友 我正在考虑将类Y分解成.h和.cpp文件,并将Y.h文件包含到X.h中,然后从那里开始。还有别的办法吗。我的意思是在代码的当前条件下,让Y成为X的朋友: 我在当前条件下遇到的错误是: > In file included from main.cpp:1:0: X.h: In function 'void swap(Y&, > Y&)': X.h:3:9: error:
> In file included from main.cpp:1:0: X.h: In function 'void swap(Y&,
> Y&)': X.h:3:9: error: 'int X::x' is private
> int x;
> ^ main.cpp:12:24: error: within this context
> swap(lhs.x_obj.x, rhs.x_obj.x);
> ^ In file included from main.cpp:1:0: X.h:3:9: error: 'int X::x' is private
> int x;
> ^ main.cpp:12:37: error: within this context
> swap(lhs.x_obj.x, rhs.x_obj.x);
我的问题是:我怎样才能使main.cpp中的Y类成为X的朋友
让Y
成为X
的朋友并不能解决这个问题。您需要使函数swap()
成为类X
的朋友,因为它试图访问X
的私有成员
class Y; // forward declaration to avoid circular dependencies
class X{
friend void swap(Y& lhs, Y& rhs);
...
};
注:您应该使用远期声明,以避免将
Y.h
包含在X.h
中,这会导致。现在我面临新的非会员功能无效互换问题(Y&lhs,Y&rhs)访问Y的私有成员,即X X_obj,因为此函数尝试访问Y的私有成员。@solti您已将其声明为类Y
,不是吗?是的。。出于某种原因,我认为多次声明朋友会造成问题。。但显然不是。。放置朋友无效掉期后(Y&lhs、Y&rhs);就像我之前做的那样worked@solti当然可以,您可以声明尽可能多的类的友元。@solti将函数参数声明为指针或引用不需要完整的类类型。所以这里允许远期申报。看见
#include "X.h"
void swap(int lhs, int rhs){
// do the swap
}
class Y{
X x_obj;
public:
friend void swap(Y& lhs, Y& rhs){
swap(lhs.x_obj.x, rhs.x_obj.x);
}
};
int main(){return 0;}
> In file included from main.cpp:1:0: X.h: In function 'void swap(Y&,
> Y&)': X.h:3:9: error: 'int X::x' is private
> int x;
> ^ main.cpp:12:24: error: within this context
> swap(lhs.x_obj.x, rhs.x_obj.x);
> ^ In file included from main.cpp:1:0: X.h:3:9: error: 'int X::x' is private
> int x;
> ^ main.cpp:12:37: error: within this context
> swap(lhs.x_obj.x, rhs.x_obj.x);
class Y; // forward declaration to avoid circular dependencies
class X{
friend void swap(Y& lhs, Y& rhs);
...
};