通过友元函数实现两个不同类中私有成员变量的数据交换

本代码中定义了两个相同的类,和一个交换信息的函数,信息交换函数同时是这两个类的友元类。

这样这个定义的信息交换函数就可以直接访问这个类的私有成员变量来进行相互间的信息交换。



//2015_July_8
// friend funciton to transmit value
#include "iostream"
using namespace std;
class CPeopleB;
class CPeopleA{
        string *ptr;
        int age;
        double salary;
    public:
        CPeopleA(){}
        CPeopleA(const string &str,int p_age, int p_salary):ptr(new string(str)),age(p_age),salary(p_salary){
        }
        friend void changeName(CPeopleA&, CPeopleB &);
        void output(){
            cout << "name = " << *ptr << endl;
            cout << "age = " << age << endl;
            cout << "salary = " << salary << endl;
        }
};
class CPeopleB{
        string *ptr;
        int age;
        double salary;
    public:
        CPeopleB(){}
        CPeopleB(const string &str,int p_age, double p_salary):ptr(new string(str)),age(p_age),salary(p_salary){
        }
        friend void changeName(CPeopleA &,CPeopleB &);
        void output(){
            cout << "name = " << *ptr << endl;
            cout << "age = " << age << endl;
            cout << "salary = " << salary << endl;
        }
};
void changeName(CPeopleA &a, CPeopleB &b){
    string *ptr;
    ptr = a.ptr;
    a.ptr = b.ptr;
    b.ptr = ptr;
    ptr = NULL;
}
int main(){
    CPeopleA tom("tom",1,1.0);
    CPeopleB jerry("jerry",2,2.0);
    changeName(tom,jerry);
    tom.output();
    jerry.output();
    return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值