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

📄 list1015.cpp

📁 teach yourself C++ in 21 days 第五版
💻 CPP
字号:
// Listing 10.15 - Copy constructors

#include <iostream>

using namespace std;

class Cat
{
  public:
    Cat();              // default constructor
    // copy constructor and destructor elided!
    int GetAge() const { return *itsAge; }
    int GetWeight() const { return *itsWeight; }
    void SetAge(int age) { *itsAge = age; }
    Cat & operator=(const Cat &);

  private:
    int *itsAge;
    int *itsWeight;
};

Cat::Cat()
{
   itsAge = new int;
   itsWeight = new int;
   *itsAge = 5;
   *itsWeight = 9;
}


Cat & Cat::operator=(const Cat & rhs)
{
   if (this == &rhs)
   return *this;
   *itsAge = rhs.GetAge();
   *itsWeight = rhs.GetWeight();
   return *this;
}


int main()
{
   Cat Frisky;
   cout << "Frisky's age: " << Frisky.GetAge() << endl;
   cout << "Setting Frisky to 6...\n";
   Frisky.SetAge(6);
   Cat Whiskers;
   cout << "Whiskers' age: " << Whiskers.GetAge() << endl;
   cout << "copying Frisky to Whiskers...\n";
   Whiskers = Frisky;
   cout << "Whiskers' age: " << Whiskers.GetAge() << endl;
   return 0;
}

⌨️ 快捷键说明

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