#include <iostream>
using namespace std;
class A;
class B
{
friend A; // 友元类
public:
B( int b ) {
this->b =
b; }
public:
void funB( A *
p );
private:
int b;
};
class A
{
public:
A( int a ) {
this->a =
a; }
public:
friend void fun(
const A & a );
// 友元函数
friend
void B::funB( A * p );
// 将B中的成员函数声明为A的友元
void Display( B *
p );
private:
int a;
};
void fun(
const A &
a )
{
cout << a.a <<
endl;
}
void B::funB( A *
p )
{
cout << p->a <<
endl;
}
void A::Display( B *
p )
{
cout << a <<
endl;
cout << p->b << endl;
// 类A中用到了类B中的私有变量,
// 因为A是B的“朋友”
}
int main()
{
A a(10);
B b(20);
a.Display( &
b );
return 0;
}
1.实话实说,将友元翻译为“朋友”,感觉会好些。
参考资料:
1.http://blog.csdn.net/insistgogo/article/details/6608672(注,这里面的boy-girl代码编译不了,不知道是否跟编译器有关,本人环境XP+VC6/VS2008)
2.http://www.cnblogs.com/skyczw/archive/2008/05/27/1208194.html
转载于:https://www.cnblogs.com/c007136/archive/2012/05/22/2513815.html