您好,欢迎来到世旅网。
搜索
您的当前位置:首页C++笔记3(拷贝构造函数)

C++笔记3(拷贝构造函数)

来源:世旅网


前言

拷贝构造函数是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;
  1. 对象以值传递的方式传入函数参数
void printStudenet(Student s2){
	cout << s2.getAge() << " " << s2.getWeight() << endl;
}
int main()
{
	Student s;
	printStudenet(s);
	return 0;
}
  1. 对象以值的传递方式从函数返回
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);
	}

所以总的来说用拷贝构造函数要注意的事情还是很多的。为了避免产生不必要的问题有以下两个方法来防止使用拷贝构造。

防止使用拷贝构造

  • 尽量使用引用
  • 私有化拷贝构造函数

一个小问题

拷贝构造函数的参数可以传对象吗?

答:不能,防止循环调用。

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- esig.cn 版权所有 湘ICP备2023023988号-3

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务