我有两个类 X
和 Y
。
Y
有一个私有(private)成员mark
,X
有一个函数getmark()
。
我将 getmark()
声明为 Y
的 friend
。
现在,如何使用friend
函数访问Y
的私有(private)成员mark
?
这是我目前的代码
#include<iostream>
using namespace std;
class X
{
public:
int getmark();
};
class Y
{
int mark;
public:
friend int X::getmark();
};
int main()
{
}
最佳答案
#include<iostream>
using namespace std;
class Y; //forward declaration of class Y
class X
{
public:
int getmark(Y);
};
class Y
{
int mark;
public:
friend int X::getmark(Y);
};
int X::getmark(Y obj){
cin>>obj.mark;
}
int main()
{
X a;
Y b;
a.getmark(b);
}
首先,当创建对象 a(X 类)时,为了向 X::getmark()< 声明
.Y
参数,需要对 Y 类进行前向声明
创建对象 b(Y 类)不会有问题,因为编译器知道 X 类存在(对于友元函数)。
然后,只需通过对象a
调用函数getmark()
。
注意:必须在声明类 Y 之后声明函数 getmark()
,否则编译器会将类 Y 视为不完整类型。
关于c++ - 一个类的另一个类的 friend 的功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25589334/