C++友元函数

#include <iostream>

/* run this program using the console pauser or add your own getch, system("pause") or input loop */

class A
{
    public:
    friend class B;
    private:
        int data;
};
class B
{
    public:
        inline void setValue(int value,A&a)
        {
            a.data = value;
            std::cout << "data : " << a.data << std::endl;
        }
        
};

int main(int argc, char** argv) 
{
    A a;
    B b;
    b.setValue(4,a);
    return 0;
}

上述例子中:

B是A的友元类,这就意味着B的对象和方法可以访问A的任意数据成员和方法,因为友元类可以访问private和protected成员,这就显得相当不安全

#include <iostream>

/* run this program using the console pauser or add your own getch, system("pause") or input loop */

class A;
class B
{
    public:
    void setValue(int x,A&a);        
};

class A
{
    public:
    friend     void B::setValue(int x,A&a);
    inline void show()
    {
        std::cout << "data : " << data << std::endl;
    }
    private:
        int data;
};
void B::setValue(int x,A&a)
{
    a.data = x;
}

int main(int argc, char** argv) 
{
    A a;
    B b;
    b.setValue(3,a);
    a.show();
    return 0;
}

第一步先声明class A,这是为了在B的成员函数能够接收到A的引用,

第二步在A中声明B的函数setValue为友函数   

第三步在类外定义友元函数

最后在main函数上应用

 

转载于:https://www.cnblogs.com/boost/p/10332238.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值