(c++常问问题十三)友元

1.友元函数(例子摘自网上)

友元函数的特点是能够访问类中的私有成员的非成员函数。友元函数从语法上看,他和普通函数相同,即在定义上和调用上和普通函数相同。下面举一例子说明友元函数的应用。

class Point
{
public:
	Point(double xx, double yy) { x=xx; y=yy; }
	friend double Distance(Point &a, Point &b);
private:
	double x, y;
};

double Distance(Point &a, Point &b)
{
	double dx = a.x - b.x;
	double dy = a.y - b.y;
	return sqrt(dx*dx+dy*dy);
}

void main()
{
	Point p1(3.0, 4.0), p2(6.0, 8.0);
	double d = Distance(p1, p2);
}

Point类中说明了一个友元函数Distance(),他在说明时前边加friend关键字,标识他不是成员函数,而是友元函数。 他直接访问了类的私有成员

 

2.友元类(例子摘自网上)

    在这里,我们引用一个我从网上收集到的例子来说明友元类的作用:假设我们要设计一个模拟电视机和遥控器的程序。大家都之道,遥控机类和电视机类是不相包含的,而且,遥控器可以操作电视机,但是电视机无法操作遥控器,这就比较符合友元的特性了。即我们把遥控器类说明成电视机类的友元。下面是这个例子的具体代码:

#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;
}

我们在程序的第6行定义了一个TV电视机类的友元类Tele。那么程序中就可以来调用TV类中的私有成员。

好了,这就是友元类了。关于友元类,我反正是这样认为的,因为友元类有可能会破坏数据的安全性,我们还是少用为好啊!

posted @ 2016-01-29 18:25  Jensen抹茶喵  阅读(267)  评论(0编辑  收藏  举报