先举个栗子
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;
}
执行代码输出
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
总结就是:
- 对象不存在,且没用别的对象来初始化,就调用了构造函数
- 对象不存在,且用别的对象来初始化,就是拷贝构造函数
- 对象存在,用别的对象来给它赋值,就是调用赋值函数