本代码中定义了两个相同的类,和一个交换信息的函数,信息交换函数同时是这两个类的友元类。
这样这个定义的信息交换函数就可以直接访问这个类的私有成员变量来进行相互间的信息交换。
//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;
}