您的位置:首页 > 其它

友元函数、友元类、访问私有数据成员、友元关系

2010-11-18 14:56 441 查看
友元函数(friend function)
1. 什么是友元函数?
一个类的私有数据成员通常只能由类的函数成员来访问,而友元函数可以访问类的私有数据成员,也能访问其保护成员
2. 友元函数的用处体现在哪里?
2.1 使用友元函数可提高性能,如:用友元函数重载操作符和生成迭代器类
2.2 用友元函数可以访问两个或多个类的私有数据,较其它方法使人们更容易理解程序的逻辑关系
3. 使用友元函数前应注意:
3.1 类的友元函数在类作用域之外定义,但可以访问类的私有和保护成员
3.2 尽管类定义中有友元函数原型,友元函数仍然不是成员函数
3.3 由于友元函数不是任何类的成员函数,所以不能用句柄(对象)加点操作符来调用
3.4 public, private, protected成员访问符与友员关系的声明无关,因此友元关系声明可在类定义的任何位置,习惯上在类定义的开始位置
3.5 友元关系是指定的,不是获取的,如果让类B成为类A的友元类,类A必须显式声明类B为自己的友元类
3.6 友元关系不满足对称性和传递性
3.7 如果一个友元函数想与两个或更多类成为友元关系,在每个类中都必须声明为友元函数
4. 注:由于C++属于混合语言,常在同一个程序中采用两种函数调用且这两种函数调用往往是相反的。类C语言的调用将
基本数据或对象传递给函数,C++调用则是将函数(或信息)传递给对象

实例1. 友元函数的声明、定义与使用


#include <iostream>


using namespace std;




class Car






{


friend void display(Car); //类"Car"的朋友display() //友元函数的声明


private:


int speed;


char color[20];


public:


void input( )






{


cout<<"Enter the color : ";


cin>>color;


cout<<"Enter the speed : ";


cin>>speed;


}


};




void display(Car x) //友元函数的定义






{


cout<<"The color of the car is : "<<x.color<<endl;


cout<<"The speed of the car is : "<<x.speed<<endl;


}




int main( )






{


Car mine;


mine.input( ); //访问成员函数


display(mine); //友元函数的使用 //将对象"mine"传给友元函数


return 0;


}


输出结果:
Enter the color: green 回车
Enter the speed: 100 回车
The color of the car is : green
The speed of the car is : 100

实例2. 将一个函数声明为多个类的友元


#include <iostream>


using namespace std;




class Virus; //类'Virus'未定义前要用到,需事先告诉编译器'Virus'是一个类




class Bacteria






{


private:


int life;


public:




Bacteria()

{ life=1; }


friend void Check(Bacteria, Virus); //类'Bacteria'中,将Check声明为友元函数


};




class Virus






{


private:


int life;


public:




Virus() : life(0)

{}


friend void Check(Bacteria, Virus); //类'Virus'中,将Check声明为友元函数


};




void Check (Bacteria b, Virus v) //友元函数的定义






{


if (b.life==1 || v.life==1)






{


cout<<"/nSomething is alive.";


}


if (b.life==1)






{


cout<<"/nA bacteria is alive.";


}


if (v.life==1)






{


cout<<"/nA virus is alive.";


}


}




int main()






{


Bacteria fever;


Virus cholera;


Check(fever, cholera); //友元函数的调用


return 0;


}

输出结果:
Something is alive.
A bacteria is alive.

友元类(friend class)
1. 友元类可以访问与之为友元关系的类的所有私有成员
2. 友元类使用较少

实例: 友元类


#include <iostream>


using namespace std;




class Add






{


private:


int x,y;


public:


Add()






{


x=y=4;


}


friend class Support; //类'Support'现在是类'Add'的朋友


};




class Support






{


public:


void Sum(Add ob)//此函数可访问类'Add'的所有私有成员






{


cout<<"The sum of the 2 members is : "<<(ob.x+ob.y)<<endl;


}


};






int main()






{


Add ad;


Support sup;


sup.Sum(ad);


return 0;


}

输出结果:
The sum of the 2 members is : 8
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: