什么时候调用拷贝构造函数
1. 调用函数时,实参是对象,形参不是引用类型
- 如果函数的形参是引用类型,就不会调用拷贝构造函数
#include "Human.h"
using namespace std;
//函数传值,会自动调用拷贝构造函数
//进行值传递的时候, 执行:Human man = h1;
void showMsg(Human man) {
man.description();
}
//如果函数的形参是引用, 不会调用拷贝构造函数
void showMsg1(const Human & man) {
//添加了const后,不可以调用没有const的成员函数
//man.setAddr((char*)"美国");
man.description();
}
//如果函数的形参是指针类型,不会调用拷贝构造函数
void showMsg2(const Human* man) {
man->description();
}
int main(void) {
Human h1;
//初始化调用拷贝构造函数
Human h2= h1; //自动调用拷贝构造函数
Human h3(h1); //自动调用拷贝构造函数
//1. 初始化的时候调用拷贝构造函数
h1.description();
h2.description();
h3.description();
//2. 函数传值的时候调用拷贝构造函数
showMsg(h1); //普通参数,调用拷贝构造函数
showMsg1(h1); //引用参数,不调用拷贝构造函数
showMsg2(&h1); //指针参数,不调用拷贝构造函数
system("pause");
return 0;
}
2. 函数的返回类型是类,而且不是引用类型
- 如果函数的返回值是引用,就不会调用拷贝构造函数
#include "Human.h"
using namespace std;
//返回值为普通参数, 调用拷贝构造函数
Human getBetterMan1(const Human &h1, const Human &h2) {
if (h1.getAge() > h2.getAge()) {
return h1;
} else {
return h2;
}
}
//返回值是对象的引用, 不会调用拷贝构造函数
const Human& getBetterMan2(const Human& h1, const Human& h2) {
if (h1.getAge() > h2.getAge()) {
return h1;
} else {
return h2;
}
}
int main(void) {
Human h1("张三", 18, "男");
Human h2("李四", 20, "男");
//函数返回临时对象, 调用拷贝构造函数
getBetterMan1(h1, h2);
//函数返回值是引用, 不调用拷贝构造函数
getBetterMan2(h1, h2);
system("pause");
return 0;
}
3. 对象数组的初始化列表中,使用对象
#include "Human.h"
using namespace std;
int main(void) {
Human F1("道明寺", 18, "男");
Human F2("花泽类", 17, "男");
Human F3("西门", 17, "男");
Human F4("美作", 17, "男");
//数组列表初始化,会调用拷贝构造函数
Human Meteor[4] = { F1, F2, F3, F4 };
for (int i = 0; i < sizeof(Meteor)/ sizeof(Meteor[0]); i++) {
Meteor[i].description();
}
system("pause");
return 0;
}