友元机制

#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.youkuaiyun.com/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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值