前言
拷贝构造函数是C++类这一块知识点里最复杂的知识点之一,所以拿出到单独一个博客来讲述这一块知识点。
拷贝构造函数
用途
通过一个对象复制出两一个对象(默认存在)
声明
class Student {
private:
int age;
int weight;
public:
Student() {
age = 1;
weight = 8;
}
//拷贝构造函数
Student(const Student& rgh) {
this->age = rgh.age;
this->weight = rgh.weight;
}
};
什么时候调用拷贝构造函数
- 对象需要通过另一个对象初始化
Student s2 = s;
- 对象以值传递的方式传入函数参数
void printStudenet(Student s2){
cout << s2.getAge() << " " << s2.getWeight() << endl;
}
int main()
{
Student s;
printStudenet(s);
return 0;
}
- 对象以值的传递方式从函数返回
Student getStudent() {
Student s;
return s;
}
int main()
{
Student s = getStudent();
return 0;
}
浅拷贝、深拷贝
说到拷贝就有浅拷贝和深拷贝之分。拷贝构造函数也有这个区别。
通俗的来讲浅拷贝就是两个变量指向了同一块存储空间,和之前提到的引用一样。深拷贝就是两个变量指向两片不同的内存,只不过两片内存存储的内容一样。
浅拷贝:
Student(const Student& rgh) {
this->age = rgh.age;
this->weight = rgh.weight;
this->name = rgh.name;
}
深拷贝:
我这里又重新声明了一个空间,所以在析构函数中增加了free()用来释放空间。
~Student() {
free(this->name);
}
Student(const Student& rgh) {
this->age = rgh.age;
this->weight = rgh.weight;
this->name = (char*)malloc(12);
strcpy(this->name, rgh.name);
}
所以总的来说用拷贝构造函数要注意的事情还是很多的。为了避免产生不必要的问题有以下两个方法来防止使用拷贝构造。
防止使用拷贝构造
- 尽量使用引用
- 私有化拷贝构造函数
一个小问题
拷贝构造函数的参数可以传对象吗?
答:不能,防止循环调用。