Copy Control Example
复制构造函数, 赋值操作符 operator = ,析构函数 总称为复制控制 (Copy Control)
e.g.:
Code:
#include <iostream>
using namespace std;
class T{
public:
T(){ cout<<"T constructor."<<endl; }
T(const T& tobj){
cout<<" T copy construct from T:"<<&tobj<<endl;
t=tobj.t;
}
//若声明为explicit,则隐式调用
/*explicit */
T(int tmp):t(tmp){
cout<<"T constructor from int."<<tmp<<endl;
}
~T(){ cout<<"T destructor. instance:"<<(int)this<<",t value:"<<t<<endl; }
T& operator =(const T& tobj){
cout<<" operator =, from:"<<hex<<&tobj<<",to:"<<hex<<(int)this<<endl;
this->t=tobj.t;
return *this;
}
//前自加操作符
T& operator ++(){
++t;
return *this;
}
//后自加操作符
T operator ++(int){
T tmp(*this);
++ this->t;
return tmp;
}
void print(){
cout<<"addr:0x"<<hex<<(int)this<<".t="<<t<<endl;
}
private:
int t;
};
int main()
{
T t=1;
//t.print();
t=2; //生成一个临时对象 tmp(2),再调用operator =方法,将其值赋给t
//t.print();
/*
cout<<"T 自加之前"<<endl;
t.print();
++t;
cout<<"T 自加之后"<<endl;
t.print();
T t2=++t;
t.print();
t2.print();
*/
cout<<"后加操作测试"<<endl;
T t3= t++;
t.print();
t3.print();
cin.get();
return 0;
}

浙公网安备 33010602011771号