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

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
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值