概述
本文主要讲解C++默认构造函数,拷贝构造函数和赋值构造函数在哪些场景下会被调用到
代码
类定义
class A{
public:
A() { cout<<"construct function"<<endl; }
A(const A& other) {
cout<<"copy construct function"<<endl;
}
A& operator=(const A& other) {
cout << "operator construct function" << endl;
return *this;
}
};
场景一
调用代码
int main() {
A a; // default construct function
A b(a); // copy construct function
A c = a; // also copy construct function
b = c; // assignment construct function
return 0;
}
输出
construct function
copy construct function
copy construct function
operator construct function
注:虽然对于c的赋值使用的是等号,但是调用的仍然是拷贝构造函数
场景二
调用代码
int main() {
A a[2]; // twice call default construct function
a[1] = a[0]; // assignment construct function
return 0;
}
输出
construct function
construct function
operator construct function