1.定义: 当一个类B成为了另外一个类A的“朋友”时,那么类A的私有和保护的数据成员就可以被类B访问。我们就把类B叫做类A的友元。
2.注意事项:值得提醒的是友员关系是单项关系,但是如果要相互作用的话,需要设置相互关系,这种关系在现实生活中的朋友关系差别有点大,呵呵~,而且这种关系尽量避免。
3.具体代码:
例一.
#include <iostream>
using namespace std;
class TV
{
public:
friend class Tele;
TV():on_off(off),volume(20),channel(3),mode(tv){}
private:
enum{on,off};
enum{tv,av};
enum{minve,maxve=100};
enum{mincl,maxcl=60};
bool on_off;
int volume;
int channel;
int mode;
};
class Tele
{
public:
void OnOFF(TV&t){t.on_off=(t.on_off==t.on)?t.off:t.on;}
void SetMode(TV&t){t.mode=(t.mode==t.tv)?t.av:t.tv;}
bool VolumeUp(TV&t);
bool VolumeDown(TV&t);
bool ChannelUp(TV&t);
bool ChannelDown(TV&t);
void show(TV&t)const;
};
bool Tele::VolumeUp(TV&t)
{
if (t.volume<t.maxve)
{
t.volume++;
return true;
}
else
{
return false;
}
}
bool Tele::VolumeDown(TV&t)
{
if (t.volume>t.minve)
{
t.volume--;
return true;
}
else
{
return false;
}
}
bool Tele::ChannelUp(TV&t)
{
if (t.channel<t.maxcl)
{
t.channel++;
return true;
}
else
{
return false;
}
}
bool Tele::ChannelDown(TV&t)
{
if (t.channel>t.mincl)
{
t.channel--;
return true;
}
else
{
return false;
}
}
void Tele::show(TV&t)const
{
if (t.on_off==t.on)
{
cout<<"电视现在"<<(t.on_off==t.on?"开启":"关闭")<<endl;
cout<<"音量大小为:"<<t.volume<<endl;
cout<<"信号接收模式为:"<<(t.mode==t.av?"AV":"TV")<<endl;
cout<<"频道为:"<<t.channel<<endl;
}
else
{
cout<<"电视现在"<<(t.on_off==t.on?"开启":"关闭")<<endl;
}
}
int main()
{
Tele t1;
TV t2;
t1.show(t2);
t1.OnOFF(t2);
t1.show(t2);
cout<<"调大声音"<<endl;
t1.VolumeUp(t2);
cout<<"频道+1"<<endl;
t1.ChannelUp(t2);
cout<<"转换模式"<<endl;
t1.SetMode(t2);
t1.show(t2);
return 0;
}
例二.
#include <iostream>
#include <cstring>
using namespace std ;
//声明教师类
class Techer ;
//学生类
class Student
{
private:
string name ;
int age ;
char sex ;
int score ;
public :
Student(string name , int age , char sex , int score);
void stu_print(Techer &tech);
};
//教师类
class Techer
{
private:
string name ;
int age ;
char sex ;
int score ;
public :
Techer(string name , int age , char sex , int score);
//声明一个友元类
friend Student ;
};
//Student类的构造函数的实现
Student::Student(string name , int age , char sex , int score)
{
this->name = name ;
this->age = age ;
this->sex = sex ;
this->score = score ;
}
//Techer类的构造函数的实现
Techer::Techer(string name , int age , char sex , int score)
{
this->name = name ;
this->age = age ;
this->sex = sex ;
this->score = score ;
}
//打印Student类中的私有成员和Techer的私有成员
void Student::stu_print(Techer &tech)
{
//用this指针访问本类的成员
cout << this->name << endl ;
cout << this->age << endl ;
cout << this->sex << endl ;
cout << this->score << endl ;
//访问Techer类的成员
cout << tech.name << endl ;
cout << tech.age << endl ;
cout << tech.sex << endl ;
cout << tech.score << endl ;
}
int main(void)
{
Student stu1("YYX",24,'N',86);
Techer t1("hou",40,'N',99);
stu1.stu_print(t1);
return 0 ;
}