C++ Primer Plus 随记(第十一章)

1. operator+() :重载+运算符 operator* ():重载*运算符  使得可以直接对类类对象进行+ 或 * 操作

假设 district, sid, sara 是类Salaperson的对象,可编写:

district=sid+sara;// 等价于下一句 ,这两个都调用operator+()方法,sid是调用对象,sara作为参数被传递的对象。

district=sid.operator+(sara);

2.重载运算符不必是成员函数,但必须至少有一个操作数是用户定义的类型。(有些运算符只能通过成员函数重载  = 、() [ ] ->)

假设Time类 class Time{ privates: int hours; int minutes;  public: ...........};

3.友元:友元函数,友元类,友元成员函数。 可以访问类的私有数据

(要实现加法或乘法的交换律,必须用友元函数重载加法或乘法。)

4.(1)创建友元函数原型放在类声明中但它不是成员函数,并在声明前加关键字friend 
friend Time operator* (double m,const Time & t); //返回值是Time类

//虽然放在类声明中,但它不是成员函数,不能使用成员运算符句点 来调用,但与成员函数有相同的权限

(2)定义友元函数:不用类限定符::,定义时不加关键字friend

Time operator* (double m,const Time & t){...........}

5.如果要为类重载运算符,并将非类的项作为其的第一操作数,则可以用友元函数来反转操作数顺序

6.重载<<运算符:

(1)使用友元函数第一种:

void operator<<(ostream &os, const Time &t){

os<<t,hours<<"hours, "<<t.minutes<<" minutes."; } //cout是ostream类的对象,通过os引用cout对象。应该引用cout本身,而                        //不 是它的拷贝,该函数按引用(而不是按值)来传递参数。当创建的一个新的对象被返回时,不应该用引用返回。

当trip是Time的对象时,可以使用cout<<trip;  输出4 hours, 25 minutes

(2)使用友元函数第二种,这种也可以用于输出写入文件中

ostream & operator<<(ostream &os, const Time &t){  //与第一种相比,有返回类型ostream &

os<<t,hours<<"hours, "<<t.minutes<<" minutes.";

return os; }

可以实现:cout<<"Trip time: "<<trip<<" (Tuesday)\n";

7. 当成员函数或友元函数的代码很短时,可以将声明和定义同时进行,写在类声明中,这样函数变成了内联函数。

8 对很多运算符,可以选择使用成员函数或非成员函数来实现运算的重载。如:

Time operator+(const Time &t) const; //成员函数

friend Time operator+( const Time &t1, const Time &t2 ); //非成员函数 

8.在名称空间VECTOR中定义了类vector的成员函数和友元函数时,友元函数要使用类中常量REC时, vector::REC

外部声明对象时vector folly(20 ,30 , VECTOR::vector::REC);

9. 类的自动转换:只有接受一个参数的构造函数才能作为转换函数。

class Stonewt
{ 
private: 
  enum {Lbs_per_stn=14};
  int stone;
  double pds_left;
  double pounds;
public:
  Stonewt(double lbs);
  Stonewt(int stn,double lbs);
  Stonewt();
  ~Stonewt();
};

(1)将int类型转换为类Stonewt类型:(只有一个参数的类构造函数用于将类型与该参数相同的值转换为类类型

Stonewt  wall=325.25; //用Stonewt(double)来设置全部3个成员,将double类型赋值给类对象,转换为类类型

Stonewt  taft=325; //int先转换为double,再用Stonewt(double)来设置全部3个成员。

(2)将类类型转化到其他类型:需要转换函数,即有用户定义的强制类型转换。转换函数是类成员,无返回类型,无参数,名为 operator typeName(),其中typeName为对象将被转换成的类型。

Stonewt wolfe(285.7);

double host=double (wolfe); //#1  or    double host=(double)  wolfe; //#2

要实现#1和#2,需要在类的方法中声明 转换为double类型的函数原型: operator double() const; //转换函数

Stonewt walls(20,3);

double star=walls; // 右侧是类类型,左侧是double,编译器将先查看是否有匹配的转换函数,有则隐式调用编译成功,无则出错

不需要编译器自动寻找匹配的编译函数来自动转换 ,可以用关键字explicit来强制转换:

  explicit operator int() const;  //仅被显示调用

10. 转换函数可以用非转换函数来替换:

Stonewt::operator int() {return int (pounds+0.5); }  调用语句:  int plb=walls;

替换为:

int  Stonewt::Stone_to_Int()  {return int (pounds+0.5); }

则调用语句为: int plb=walls.Stone_to_Int();

猜你喜欢

转载自blog.csdn.net/lvliang2017232003/article/details/86139452