1.自定义拷贝构造函数
#include<iostream>
#include<string>
#include<string.h>
using namespace std;
class Human
{
private:
/* data */
int age;
std::string name;
public:
Human(/* args */);
~Human();
Human(const Human&);
int get();
};
Human::Human(/* args */)
{
age =10;
name="hello";
}
Human::~Human()
{
}
Human::Human(const Human& h)
{
this->age =h.age +1;
this->name=h.name;
}
int Human::get() {
return this->age;
}
int main(){
Human h;
Human h2(h);
std::cout << h2.get() << std::endl;
return 0;
}
2.合成的拷贝构造函数
属于浅拷贝
#include<iostream>
#include<string>
#include<string.h>
using namespace std;
class Human
{
private:
/* data */
int age;
std::string name;
char* addr;
public:
Human(/* args */);
~Human();
//Human(const Human&);//不定义拷贝构造函数,编译器会生成“合成的拷贝构造函数”
int get();
};
Human::Human(/* args */)
{
age = 14;
name = "hello";
addr = new char[64];
strcpy_s(addr, 64, "China");
}
Human::~Human()
{
}
// Human::Human(const Human& h)
// {
// this->age =h.age +1;
// this->name=h.name;
// }
int Human::get() {
return this->age;
}
int main() {
Human h;
Human h2(h);
std::cout << h2.get()<< std::endl;
return 0;
}
说明:
合成的拷贝构造函数的缺点: 使用“浅拷贝”
解决方案:在自定义的拷贝构造函数中,使用‘深拷贝
Human::Human(const Human &man) {
cout << "调用自定义的拷贝构造函数" << endl;
age = man.age; //this是一个特殊的指针,指向这个对象本身
salary = man.salary;
name = man.name;
// 深度拷贝
addr = new char[64];
strcpy_s(addr, 64, man.addr);
}
什么时候调用拷贝构造函数
- 调用函数时,实参是对象,形参不是引用类型
如果函数的形参是引用类型,就不会调用拷贝构造函数
- 函数的返回类型是类,而且不是引用类型
- 对象数组的初始化列表中,使用对象。