一 浅拷贝
浅拷贝不开辟新空间,只增加一个指针,指向原有的内存。
程序测试
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <vector>
using namespace std;
class Person {
public:
//构造函数;
Person(const char* name, int age) {
this->mName = new char[strlen(name) + 1];
strcpy(this->mName, name);
this->mAge = age;
cout << "构造函数:" << endl;
}
//析构函数
~Person() {
if (this->mName != NULL) {
delete[] this->mName;
cout << "析构函数" << endl;
}
}
private:
char* mName; //指针 容易浅拷贝的问题
int mAge;
};
void test01() {
Person p("liu", 20);
vector<Person> vPerson;
vPerson.push_back(p);
}
int main(void) {
test01();
return 0;
}
程序运行出错:
因为,发生了浅拷贝,p 和 vperson两个对象指针指向同一块内存空间,析构时候,会析构两次,因此报错。
二 深拷贝
深拷贝会开辟新的内存空间,把原有的对象复制过来。见下图:
拷贝构造函数
拷贝构造函数是一种特殊的构造函数,遵循如下的规则:
1.函数名和类名一致,没有返回值。
2.必须有一个参数,参数是本类型的一个引用变量。
3.拷贝构造函数可以访问参数对象的任意成员(private也可以)。
4.若自己不提供拷贝构造函数,系统会提供默认构造函数,若自己定义,系统将不再提供。
5.系统提供的拷贝构造是浅拷贝
添加拷贝构造函数后
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <vector>
using namespace std;
class Person {
public:
//构造函数;
Person(const char* name, int age) {
this->mName = new char[strlen(name) + 1]; //分配内存
strcpy(this->mName, name);
this->mAge = age;
cout << "构造函数:" << (int)mName << endl;
}
Person(const Person& p) {
this->mName = new char[strlen(p.mName) + 1];
strcpy(this->mName, p.mName);
this->mAge = p.mAge;
cout << "person 拷贝构造函数" << endl;
}
Person& operator=(const Person& p){
//判断一下是否为空
if (this->mName != NULL) {
delete[] this->mName;
}
this->mName = new char[strlen(p.mName) + 1];
strcpy(this->mName, p.mName);
this->mAge = p.mAge;
cout << "operator = " << endl;
}
//析构函数
~Person() {
if (this->mName != NULL) {
delete[] this->mName;
cout << "析构函数:" << (int)mName << endl;
}
}
private:
char* mName; //指针 容易浅拷贝的问题
int mAge;
};
void test01() {
Person p("liu", 20);
vector<Person> vPerson;
vPerson.push_back(p);
}
int main(void) {
test01();
return 0;
}
执行结果: