什么时候调用拷贝构造函数
1. 调用函数时,实参是对象,形参不是引用类型
#include "Human.h"
using namespace std;
void showMsg(Human man) {
man.description();
}
void showMsg1(const Human & man) {
man.description();
}
void showMsg2(const Human* man) {
man->description();
}
int main(void) {
Human h1;
Human h2= h1;
Human h3(h1);
h1.description();
h2.description();
h3.description();
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;
}