@cxm-2016
2016-09-30T01:29:54.000000Z
字数 2524
阅读 2400
c++
版本:2
作者:陈小默
说明:调整了部分语句结构
通常情况下,类的私有变量是不能够被外界直接访问的,但是在某些情况下我们需要在非成员的方法中使用这些私有变量,于是C++提供了一种新的语法机制叫做友元。
以运算符重载为例,我们在上一节创建了一个Time类的例子。里面重载了*运算符。于是我们可以采用以下形式来将时间扩大三倍:
time = time * 3;
但是下面的写法有没有问题呢?
time = 3 * time;
从概念上说这两句应该具有相同的效果。但是却不能通过编译,因为我们没有对3进行过运算符重载。
通常情况我们有两种解决方案:
Time operator*(int n,const Time & t);
如果我们要使用这种方式的话就需要给所有需要被访问的私有属性设个getter方法。这样又会导致我们对外暴露出我们本想隐藏的数据。
为了解决这个问题我们引入了友元函数。
第一步:在声明中使用friend关键字声明友元函数原型:
friend Time operator*(int n,Time &t);
注意:虽然友元函数在类的声明中声明,但其不是类的成员函数,因此不能使用成员运算符调用;虽然友元函数不是成员函数,但是具有与成员函数相同的访问权限。
第二步:实现友元函数:
Time operator*(int n,Time &t){t.time*=n;return t;}
注意:因为友元函数不是成员函数,所以不能使用函数限定符
Time::;其次不要在定义中使用friend关键字,除非声明即定义。
假使我们有这样一个需求:让cout对象能够直接对Time对象进行输出。我们应该怎么办呢?根据上面的学习我们应该能够想到,就是采用友元函数对<<运算符进行重载。
#ifndef primer_time_h#define primer_time_h#include<string>#include<iostream>class Time{private:enum {SECOND_MAX=1000,MINUTE_MAX=60*1000,HOURS_MAX=60*60*1000};long long time;public:void setMinutes(int m);void setHours(int h);void setSecondes(int s);long long getLongTime();Time& operator+(Time &t);Time& operator-(Time &t);Time& operator*(int n);Time& operator/(int n);friend Time& operator*(int n,Time &t);friend std::ostream& operator<<(std::ostream &os,Time &t){int hours = int(t.time/HOURS_MAX);int minutes = int((t.time%HOURS_MAX)/MINUTE_MAX);int seconds = int(t.time%MINUTE_MAX/SECOND_MAX);os<<"Time["<<hours<<":";if(minutes<10)os<<0;os<<minutes<<":";if(seconds<10)os<<0;os<<seconds<<"]";return os;};};#endif
接下来实现代码
#include "stdafx.h"#include "time.h"void Time::setHours(int h){if(h>=0){time = time%HOURS_MAX+h*HOURS_MAX;}}void Time::setMinutes(int m){if(m>=0&&m<60){time = (time-time%HOURS_MAX)+time%MINUTE_MAX+m*MINUTE_MAX;}}void Time::setSecondes(int s){if (s>=0&&s<60){time = (time-time%MINUTE_MAX)+s*SECOND_MAX;}}long long Time::getLongTime(){return time;}Time& Time::operator+(Time &t){time+=t.getLongTime();return *this;}Time& Time::operator-(Time &t){time-=t.getLongTime();return *this;}Time& Time::operator*(int n){time*=n;return *this;}Time& Time::operator/(int n){time/=n;return *this;}Time& operator*(int n,Time &t){t.time*=n;return t;}
现在我们看一下修改后的效果
#include"stdafx.h"#include"time.h"int main(int argc, const char * argv[]) {Time t1,t2;t1.setHours(23);t1.setMinutes(59);t1.setSecondes(58);t2.setSecondes(1);t1 = t1 + 2 * t2;cout<<t1<<endl;return 0;}
这里演示了23小时59分58秒加行两个一秒钟之后的时间。
运行结果
Time[24:00:00]
这里程序很完美的完成了这个任务。
学到这里我们发现一个方法可以有多种的重载方式。对于一个重载,我们可以使用下面两种方式中的任意一种。
Time& operator+(Time &t);
friend Time& operator+(Time &t1,Time &t2);
但是,我们不能同时声明这两种方式,因为编译器无法确定具体要重载哪一个方法。
