示例代码如下:
#include<iostream>
using namespace std;
class B
{
public:
B(int a,int b):bx(a),by(b){}
private:
int bx,by;
// friend void testFriend(B& b);
};
void testFriend(B& b)
{
cout<<b.bx<<endl;
cout<<b.by<<endl;
}
int main()
{
B b(2,3);
testFriend(b);
getchar();
return 0;
}
结果:

如果:
#include<iostream>
using namespace std;
class B
{
public:
B(int a,int b):bx(a),by(b){}
private:
int bx,by;
friend void testFriend(B& b);
};
void testFriend(B& b)
{
cout<<b.bx<<endl;
cout<<b.by<<endl;
}
int main()
{
B b(2,3);
testFriend(b);
getchar();
return 0;
}
结果:


本文通过两个示例对比展示了如何在C++中定义和使用友元函数来访问类的私有成员。介绍了友元函数的基本概念及其在类设计中的应用。

641

被折叠的 条评论
为什么被折叠?



