读书人

关于C++中的复制(拷贝)构造函数解决

发布时间: 2012-09-04 14:19:30 作者: rapoo

关于C++中的复制(拷贝)构造函数

谁能用例子告诉我什么叫“ 浅复制 和 深复制 ”



[解决办法]

C/C++ code
程序实例如下:#include <iostream> using namespace std; class Cat { public:   Cat();   Cat(const Cat &);   ~Cat();   int GetAge() const { return *itsAge; }   int GetWeight() const { return *itsWeight; }   void SetAge(int age) { *itsAge=age; } private:   int *itsAge;    //实际编程并不会这样做,   int *itsWeight; //我仅仅为了示范 }; Cat::Cat() {/*构造函数,在堆中分配内存*/   itsAge=new int;   itsWeight=new int;   *itsAge=5;   *itsWeight=9; } Cat::Cat(const Cat & rhs) {/*copy constructor,实现深层复制*/   itsAge=new int;   itsWeight=new int;   *itsAge=rhs.GetAge();   *itsWeight=rhs.GetWeight(); } Cat::~Cat() {   delete itsAge;   itsAge=0;   delete itsWeight;   itsWeight=0; } int main() {   Cat Frisky;   cout << "Frisky's age: "<<Frisky.GetAge()<<endl;   cout << "Setting Frisky to 6...\n";   Frisky.SetAge(6);   cout << "Create Boots from Frisky\n";   Cat Boots=Frisky; //or Cat Boots(Frisky);   cout << "Frisky's age: " <<Frisky.GetAge()<<endl;   cout << "Boots' age : "<<Boots.GetAge()<<endl;   cout << "Set Frisky to 7...\n";   Frisky.SetAge(7);   cout << "Frisky's age: "<<Frisky.GetAge()<<endl;   cout << "Boots' age: "<<Boots.GetAge()<<endl;   return 0; } //输出: //Frisky's age: 5 //Setting Frisky to 6... //Create Boots from Frisky //Frisky's age: 6 //Boots' age : 6 //Set Frisky to 7... //Frisky's age: 7 //Boots' age: 6 

读书人网 >C++

热点推荐