做网站点击挣钱不nba最新排行
概述
本文主要讲解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 functionA b(a); // copy construct functionA c = a; // also copy construct functionb = c; // assignment construct functionreturn 0;
}
输出
construct function
copy construct function
copy construct function
operator construct function
注:虽然对于c的赋值使用的是等号,但是调用的仍然是拷贝构造函数
场景二
调用代码
int main() {A a[2]; // twice call default construct functiona[1] = a[0]; // assignment construct functionreturn 0;
}
输出
construct function
construct function
operator construct function