C++学习笔记(Thinking in C++)四

    技术2022-05-20  31

    1、运算符重载

      1 class Byte   2 {   3         unsigned char b;   4         const Byte& operator++()   5         {   6                 cout<<"++Byte"<<endl;   7                 b++;   8                 return *this;   9         }  10         const Byte& operator++(int)  11         {  12                 cout<<"Byte++"<<endl;  13                 Byte before(b);  14                 b++;  15                 return before;  16         }  17 };

    2、对象返回值问题

      1 class Interger   2 {   3         int i;   4         const Interger operator+(const Interger &left, const Interger &right)   5         {          6                 return Interger(left.i + right.i);//创建一个临时Interger对象并返回它

      7                 /* 下面会执行三个步骤:

                             a、创建tmp对象,调用构造函数; 

                             b、拷贝构造函数把tmp拷贝到外部返回值的存储单元; 

                             c、当tmp在作用域的结尾调用析构函数,

      8                  Interger tmp(left.i + right.i);   9                  return tmp;  10                  */  11         }

     12 };

    3、关键字explicit

         C++提供了关键字explicit,可以阻止不应该允许的经过转换构造函数进行的隐式转换的发生。声明为explicit的构造函数不能在隐式转换中使用。显示声明:CE e(1);CE e2(e1);这种显式调用外,其它都是非显式的。

      1 class CNoE   2 {   3 public:   4         CNoE(int i):m_num(i){}   5 private:   6         int m_num;   7 };   8   9 class CE  10 {  11 public:  12         explicit CE(int i):m_num(i){}  13         explicit CE(const CE& e):m_num(e.m_num){}  14 private:  15         int m_num;  16 };  17  18 int main(void)  19 {  20         CNoE no=1;  21         CE e1(1);  22         CE e2=1;//错误:conversion from ‘int’ to non-scalar type ‘CE’ requested  23         CE e3(e1);  24         CE e4=e1;//错误:no matching function for call to ‘CE::CE(CE&)’

     25         cout<<sizeof(CNoE)<<" "<<sizeof(CE)<<endl; //输出是:4 4;  26         return 0;  27 }


    最新回复(0)