C++中的友元(一)

来源:互联网 发布:linux 目录树 编辑:程序博客网 时间:2024/04/30 04:19

C++中的友元包括友元函数,友元类等,这篇首先介绍友元函数。友元函数是为了解决运算符重载的局限性而引入的。主要用非成员函数来完成对类中属性的访问,从而达到非成员函数完成运算符重载的目的,解决了只能把类对象放在前面调用运算符的局限性。
一:创建友元:
1.首先要将友元函数的原型放在类的声明中,并且在原型的声明前加上关键字friend

friend Time operator*(double m,const Time &t);
    2. 接下来完成对函数的定义,由于友元函数不是成员函数,所以成员函数的定义不能加上Time::的限定符。   代码,注意区别不同,友元只是弥补了缺陷不能删除之前的代码:
class Time{private:    int hours;    int minutes;public:    Time();    Time(int h,int m=0);                //这里使用了一个小的技巧,为什么m=0?因为这样就使得两个构造的函数实现了三个构造函数的作用    void AddMin(int m);    void AddHrs(int h);    void Reset(int h=0,int m=0);        //重置的时候也是不知道传几个参数,一个函数完成了三个函数的作用    Time operator+(const Time &t)const;    Time operator-(const Time &t)const;     Time operator*(double n)const;      //不使用友元与使用友元同时存在    void show() const;    friend Time operator*(double m,const Time &t);//不使用友元与使用友元同时存在};//使用友元之前Time Time::operator*(double n)const{    Time result;    long totalminutes=hours*60*n+n*minutes;    result.hours=totalminutes/60;    result.minutes=totalminutes%60;    return result;}//使用友元之后Time operator*(double m,const Time &t){    Time result;    long totalminutes=m*t.minutes+m*t.hours*60;    result.hours=totalminutes/60;    result.minutes=totalminutes%60;    return result;}

总结:类的友元函数时非成员函数,其访问权限与成员函数的访问权限相同。
二:常见的友元:重载<<运算符:
通过对<<运算符的重载,使得能直接与cout来一起显示对象的内容,这里的重载与java中的重写toString()实现了相同的作用,此点较重要,注意此处的<<重载必须使用友元函数,因为用户定义的类的对象不是调用函数的对象(该对象没有位于前面),cout是ostream的对象。
1.在类的声明中,添加函数的原型:

friend std::ostream & operator<<(std::ostream & os,const Time & t);
函数的定义为:
std::ostream & operator<<(std::ostream & os,const Time & t){    os<<t.hours<<"hours";    return os;}
0 0