list0911.cpp

来自「teach yourself C++ in 21 days 第五版」· C++ 代码 · 共 69 行

CPP
69
字号
//Listing 9.11 - Passing pointers to objects
  
#include <iostream>
  
using namespace std;
class SimpleCat
{
   public:
     SimpleCat();
     SimpleCat(SimpleCat&);
     ~SimpleCat();
  
     int GetAge() const { return itsAge; }
     void SetAge(int age) { itsAge = age; }
  
   private:
     int itsAge;
};
  
SimpleCat::SimpleCat()
{
    cout << "Simple Cat Constructor..." << endl;
    itsAge = 1;
}
  
SimpleCat::SimpleCat(SimpleCat&)
{
     cout << "Simple Cat Copy Constructor..." << endl;
}
  
SimpleCat::~SimpleCat()
{
    cout << "Simple Cat Destructor..." << endl;
}
  
const SimpleCat * const FunctionTwo 
    (const SimpleCat * const theCat);
  
int main()
{
    cout << "Making a cat..." << endl;
    SimpleCat Frisky;
    cout << "Frisky is " ;
    cout << Frisky.GetAge();
    cout << " years old" << endl;
    int age = 5;
    Frisky.SetAge(age);
    cout << "Frisky is " ;
    cout << Frisky.GetAge();
    cout << " years old" << endl;
    cout << "Calling FunctionTwo..." << endl;
    FunctionTwo(&Frisky);
    cout << "Frisky is " ;
    cout << Frisky.GetAge();
    cout << " years old" << endl;
    return 0;
}
  
// functionTwo, passes a const pointer
const SimpleCat * const FunctionTwo 
    (const SimpleCat * const theCat)
{
    cout << "Function Two. Returning..." << endl;
    cout << "Frisky is now " << theCat->GetAge();
    cout << " years old " << endl;
    // theCat->SetAge(8);   const!
    return theCat;
}

⌨️ 快捷键说明

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