首页 > 编程语言 > 详细

【C++】各种构造函数

时间:2021-01-01 22:45:04      阅读:24      评论:0      收藏:0      [点我收藏+]
class person {
public:
	int age;
	char* name;
	int namelen;
	//普通构造
	person(int age,const char* name) {
		this->age = age;
		int len = strlen(name);
		this->name = new char[len + 1];
		memcpy(this->name, name, len+1);
		this->namelen = len;
	}
	//拷贝构造函数
	person(person& t) {
		cout << "拷贝构造函数" << endl;
        //深拷贝
		if (t.name != NULL) {
			this->name = new char[t.namelen+1];
			memcpy(this->name, t.name, t.namelen + 1);
			this->namelen = t.namelen;
			this->age = t.age;
		}
	}
	//移动构造函数
	person(person&& t) {
		cout << "移动构造函数" << endl;
		if (t.name != NULL) {
			this->name = t.name;
			t.name = nullptr;
			this->namelen = t.namelen;
			this->age = t.age;
		}
	}
};

int main() {
	
	const char *str= "hello";

	//普通构造
	person pa(24, str);
	//拷贝构造(默认浅拷贝)
	person pb(pa);
	person pd=pa;
	//移动构造(无默认)
	person pc=move(pa);
	
}

【C++】各种构造函数

原文:https://www.cnblogs.com/kidtic/p/14219874.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!