【C++】各种构造函数

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);
	
}
posted @ 2021-01-01 13:11  峰绘の琴师  阅读(197)  评论(0编辑  收藏  举报