• 【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);
    	
    }
    
  • 相关阅读:
    红黑树
    二叉搜索树
    散列表
    快速排序
    堆排序
    归并排序
    插入排序
    Shell脚本之:函数
    Shell脚本之:退出循环
    ACM刷题之路(四)2018暑假实验室集训——深广搜专题题解
  • 原文地址:https://www.cnblogs.com/kidtic/p/14219874.html
Copyright © 2020-2023  润新知