运算符重载 友元函数
重载运算符格式:operator 可重载运算符(argument-list)
class Time
{
private:
int hours;
public:
Time operator+(const Time & t) const;
}
Time Time::operator+(const Time & t) cosnt
{
Time sum;
sum.hours=hours+t.hours;
return sum;
}
//Time A,B,C,D;
A=B+2.75;
//将转换为
A=B.operator+(2.75);
A=B+C+D;
//先转换为
A=B.operator+(C+D);
//在转换为
A=B.operator+(C.operator+(D));
//所以operator+()函数要返回符合格式的类型
可重载的运算符
重载限制
友元是除了共有类方法外,另一种可以访问类对象私有部分的形式。友元有3种:
使用关键字friendfriend Time operator*(double m,const Time & t);
operator*()函数是在类声明中声明的,但它不是成员函数,因此不能使用成员运算符来调用operator*()函数不是成员函数,但它与成员函数的访问权限相同//函数定义,不要使用Time::限定符和firend关键字
Time operator*(double m,const Time & t)
{
Time result;
result.hours=t.hours+m
return result;
}
//Time A,B;
A=2.75+*B;
//将转换为
A=operator*(2.75,B);
友元是否有悖于OOP?
//同时使用两种方式的重载运算符
T1=T2+T3;
//将转换为
T1=T2.operator+(T3);
T1=operator+(T2+T2);
//将被视为二义性,导致编译错误
Stonewt(double lbs);
Stonewt myCat;
myCat=19.6;//隐式转换
Stonewt(int stn,double lbs=1);
Stonewt myCat;
myCat=19;//自动类型转换
C++新增了关键字explicit用于关闭这种自动特性
explicit Stonewt(double lbs);//关闭隐式转换,允许显示转换
Stoewt myCat;
myCat=19.6; // not valid
myCat=Stonewt(19.6); // ok
myCat=(Stonewt)19.6; // ok
什么情况下会发生隐式转换
Stonewt Jumbo;
Jumbo=7000;//int先转换为double
Stonewt(long l);
Jumbo=7000;// fail int可以转换为double或long,存在二义性
Stonewt wolfe(28.7);
double host=wolfe;//?? possible ??
//使用转换函数
double host=double(wolfe);
double host=(double)wolfe;
如何创建转换函数?
operator double();自动应用类型转换
Stonewt wells(20,3);
double star =wells;//编译器会查找与此匹配的转换函数
如何关闭自动应用类型转换?
explicit可用于转换函数class Stonewt
{
Explicit operator int() const;
}
Stonewt::operator int(){return int(pounds+0.5);}
替换为int Stonewt::Stone_to_int(){return int(pounds+0.5);}