构造函数,拷贝构造和赋值运算符调用时机,explicit,

  1 #include<iostream>
  2 #include <stdio.h>
  3 using namespace std;
  4 class test{
  5 int mvalue;
  6 public:
  7         explicit test(int i=0){ //此处的explicit表明该构造函数需要显示的调用
  8                 printf("%s(%d)
", __func__, i);
  9                 mvalue = i;
 10         }
 11 
 12         test& operator=(const test& that)
 13         {
 14             printf("%s(test&)
", __func__);
 15             mvalue = that.mvalue;
 16             return *this;
 17         }
 18 
 19         test(const test& that)
 20         {
 21             printf("%s(test&)
", __func__);
 22             mvalue = that.mvalue;
 23         }
 24 
 25         test& operator=(const int& that)
 26         {
 27             printf("%s(int&)
",__func__);
 28             mvalue = that;
 29             return *this;
 30         }
 31 
 32         int value(){
 33                 return mvalue;
 34         }
 35         test& operator++(){
 36                 ++mvalue;
 37                 return *this;
 38         }
 39         //后++
 40         test operator++(int){
 41                 //临时对象
 42                 //test ret(mvalue);
 43                 int ret = mvalue;
 44                 mvalue++;
 45                 return test(ret); //此处由于在有参构造的地方加上了explicit在需要显示的调用test(int i);
 46         }
 47 };
 48 
 49 int main(){
 50         test t(0);
 51         test tt = t++;
 52         test t1(t); //<=等价=> test t1 = t 其本质还是调用拷贝构造函数。在对象创建出来之前编译器禁止使用=号操作符重载函数,只能调用构造函数;
 53         t1 = t; //  <=等价=> t1.operator=(t);
 54         cout << t1.value() << endl;
 55         cout << tt.value() << endl;
 56         cout << t.value() << endl;
 57         return 0;
 58 }
原文地址:https://www.cnblogs.com/DXGG-Bond/p/11883342.html