C++高级主题之复制构造函数
时间:2011-05-19 来源:COS
复制构造函数
#include<string> #include<iostream> using namespace std; class Department { public: Department(string _name); Department(string _name,char* _address); ~Department(); Department& operator=(const Department& b); Department(const Department &b);//复制构造函数 void print()const; private: string name; char* address; }; Department::Department(string _name) { name=_name; address=NULL; cout<<"Constructor:"; print(); } Department::Department(string _name,char* _address) { name=_name; address=new char[strlen(_address)+1]; strcpy(address,_address); cout<<"Constructor:"; print(); } Department::~Department() { cout<<"Destructor:"; print(); delete []address; } Department::Department(const Department& b) { cout<<"复制构造函数:"; b.print(); name=b.name; if(b.address==NULL) address=NULL; else { address=new char[strlen(b.address)+1]; name=b.name; strcpy(address,b.address); } } Department& Department::operator=(const Department& b) { cout<<"Assignment:"; print(); cout<<"= "; b.print(); if(this != &b) { name=b.name; delete[] address; if(b.address==NULL) address=NULL; else { address=new char[strlen(b.address)+1]; name=b.name; strcpy(address,b.address); } } return *this; } void Department::print()const { cout<<"name="<<name<<",address="; if(address==NULL) cout<<"NULL"; else cout<<address; cout<<"\n"; } /* void fun(Department x) { string p=x.name;//error cannot access private variable }*/ void main() { Department shipping("shipping"); Department qc("quality control","china"); Department dept(qc); dept=shipping; }
程序运行结果:
相关阅读 更多 +