先舉個栗子
class C {
public:
C(){
cout << "none argument constructor called" << endl;
}
C(int a):i(a) {
cout << "constructor called" << endl;
}
C(const C& c) : i(c.i) {
cout << "copy constructor called" << endl;
}
C& operator=(const C& c) {
cout << "operator = called" << endl;
if(this == &c){
return *this;
}
i = c.i;
return *this;
}
~C(){
cout << "destructor called" << endl;
}
private:
int i;
};
int main(){
C c1(1);
cout << "=======" << endl;
C c2(c1);
cout << "=======" << endl;
C c3;
c3 = c2;
cout << "=======" << endl;
C c4 = c3;
return 0;
}
執(zhí)行代碼輸出
constructor called
=======
copy constructor called
=======
none argument constructor called
operator = called
=======
copy constructor called
destructor called
destructor called
destructor called
destructor called
Program ended with exit code: 0
總結就是:
- 對象不存在译株,且沒用別的對象來初始化,就調用了構造函數
- 對象不存在挺益,且用別的對象來初始化歉糜,就是拷貝構造函數
- 對象存在,用別的對象來給它賦值望众,就是調用賦值函數