æä¼éç¨æ·±å¤å¶æé å½æ°å®ç°Copy对象ï¼èä¸æ¯éè½½=è¿ç®ç¬¦ã
åå :å 为使ç¨äºå¨æå
ååé
,å½è¢«Copyç对象使ç¨å®æ¯æ¶ææå½æ°å°éæ¾å
¶æç³è¯·çå
å空é´,ä½Copyç对象è¿å¨ä½¿ç¨ä¸,æ¤æ¶éæ¾å
åå°é æç¨åºå´©æºã
#include<iostream>
using namespace std;
namespace ns{
class Person{
public:
Person(){}
Person(char *name, int age,char *sex){
this->name = new char[strlen(name) + 1];
strcpy(this->name, name);
this->sex = new char[strlen(sex) + 1];
strcpy(this->sex, sex);
this->age = age;
}
// æ·±å¤å¶æé å½æ°
Person(const Person &obj){
this->name = new char[strlen(obj.name) + 1];
strcpy(this->name, obj.name);
this->sex = new char[strlen(obj.sex) + 1];
strcpy(this->sex, obj.sex);
this->age = obj.age;
}
~Person(){
delete this->sex;
delete this->name;
}
void print(){
cout << "name=" << this->name << "\tage="
<< this->age << "\tsex=" << this->sex << endl;
}
private:
char *name;
int age;
char *sex;
};
}
int main(int argc, char *argv[]){
ns::Person person("James", 20, "ç·");
person.print();
ns::Person person2("Lisa", 22, "女");
person2.print();
ns::Person deepCopy=person2;
deepCopy.print();
return 0;
}