学习笔记

C++PrimerPlus类的使用
Publish: 2018/7/23   

运算符重载 友元函数

运算符重载

重载运算符格式:
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+()函数要返回符合格式的类型

可重载的运算符

重载限制

  1. 重载后的运算符必须至少有一个操作数是用户定义的类型,这将防止用户为标准类型重载运算符
  2. 使用运算符时不能违反运算符原来的语法规则
  3. 不能创建新运算符
  4. 表中的大多数运算符都可以通过成员或非成员函数进行重载,但下面的运算符只能通过成员函数重载

友元

友元是除了共有类方法外,另一种可以访问类对象私有部分的形式。友元有3种:

创建友元

使用关键字friend
friend Time operator*(double m,const Time & t);

//函数定义,不要使用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;

如何创建转换函数?

自动应用类型转换

Stonewt wells(20,3);
double star =wells;//编译器会查找与此匹配的转换函数

如何关闭自动应用类型转换?

class Stonewt
{
    Explicit operator int() const;
}

Stonewt::operator int(){return int(pounds+0.5);}
替换为
int Stonewt::Stone_to_int(){return int(pounds+0.5);}



← C++PrimerPlus类和动态内存分配 C++PrimerPlus函数探幽 →

Powered by Hexo, Theme designs by @hpcslag.
Style-Framework Tocas-UI designs by @yamioldmel