Copy Control Example
1672 ワード
構造関数のコピー、割り当てオペレータoperator=、構造関数の総称はコピー制御(Copy Control)です.
e.g.:
Code:
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;
}