#include <iostream>
using namespace std;classObject{};
int main(){//正确,调用编译器提供的默认构造函数
Object obj_1;//错误,No constructor could take the source type, or constructor overload resolution was ambiguous
Object obj_2(10);//正确,调用编译器提供的默认拷贝构造函数
Object obj_3(obj_1);system("pause");return0;}
如果用户自定义了有参构造函数,编译器不再提供默认构造函数,但会提供拷贝构造函数。
#include <iostream>
using namespace std;classObject{public:Object(int){
cout <<"calling the parametric constructor"<< endl;}};
int main(){//错误, no appropriate default constructor available
Object obj_1;//正确, 调用自定义的有参构造函数
Object obj_2(10);//正确, 调用编译器提供的默认拷贝构造函数
Object obj_3(obj_2);system("pause");return0;}
如果用户自定义了拷贝构造函数,编译器不再提供其他构造函数。
#include <iostream>
using namespace std;classObject{public:Object(const Object& obj){
cout <<"calling the self-define copy constructor"<< endl;}};
int main(){//错误, no appropriate default constructor available
Object obj_1;//错误, Object::Object(const Object &)': cannot convert argument 1 from 'int' to 'const Object &
Object obj_2(10);system("pause");return0;}
2. 拷贝构造函数调用时机
使用一个已存在对象初始化一个新对象。
值传递的方式给函数参数传值。
值方式返回函数的局部对象。
#include <iostream>
using namespace std;classObject{public:Object(){
cout <<"calling the default constructor"<< endl;}Object(int){
cout <<"calling the parametric constructor"<< endl;}Object(const Object& obj){
cout <<"calling the copy constructor"<< endl;}~Object(){
cout <<"calling the destructor"<< endl;}};voidtest01(Object obj){return;}
Object test02(){
Object obj_4;//calling the default constructorreturn obj_4;}
int main(){
Object obj_1;//calling the default constructor
Object obj_2(10);//calling the parametric constructor//使用一个已存在对象初始化一个新对象
Object obj_3(obj_1);//calling the copy constructor//值传递的方式给函数参数传值test01(obj_1);//calling the copy constructor//值方式返回函数的局部对象
Object obj_5 =test02();//calling the copy constructorsystem("pause");return0;}