⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 hour13_3.cpp

📁 《24学时精通c++》的随书源码的下半部分。欢迎下载学习。
💻 CPP
字号:
 // Listing 13.3

 // Copy constructors

 #include <iostream>

 

 class CAT

 {

 public:

     CAT();                         // default constructor

     CAT (const CAT &);     // copy constructor

     ~CAT();                         // destructor

     int GetAge() const { return *itsAge; }

     int GetWeight() const { return *itsWeight; }

     void SetAge(int age) { *itsAge = age; }

 

 private:

     int *itsAge;

     int *itsWeight;

 };

 
/* comment out our constructor and use the default

 CAT::CAT()

 {

     itsAge = new int;

     itsWeight = new int;

     *itsAge = 5;

     *itsWeight = 9;

 }
end of commented out constructor */

// Now the code won't behave like you expect (if it compiles) 
// because space is not allocated for itsAge or itsWeight to point to!
// When we try to change Age with SetAge, we may get a segmentation violation
// Since the pointer doesn't point anywhere correct.

 

 CAT::CAT(const CAT & rhs)

 {

     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;

     std::cout << "frisky's age: " << frisky.GetAge() << "\n";

     std::cout << "Setting frisky to 6...\n";

     frisky.SetAge(6);

     std::cout << "Creating boots from frisky\n";

     CAT boots(frisky);

     std::cout << "frisky's age: " << frisky.GetAge() << "\n";

     std::cout << "boots' age: " << boots.GetAge() << "\n";

     std::cout << "setting frisky to 7...\n";

     frisky.SetAge(7);

     std::cout << "frisky's age: " << frisky.GetAge() << "\n";

     std::cout << "boot's age: " << boots.GetAge() << "\n";

     return 0;

 }

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -