list0810.cpp

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

CPP
55
字号
// Listing 8.10 - Using pointers with const methods

#include <iostream>
using namespace std;

class Rectangle
{
   public:
     Rectangle();
     ~Rectangle();
     void SetLength(int length) { itsLength = length; }
     int GetLength() const { return itsLength; }
     void SetWidth(int width) { itsWidth = width; }
     int GetWidth() const { return itsWidth; }
 
   private:
     int itsLength;
     int itsWidth;
};
 
Rectangle::Rectangle()
{
    itsWidth = 5;
    itsLength = 10;
}
 
Rectangle::~Rectangle()
{}
 
int main()
{
    Rectangle* pRect =  new Rectangle;
    const Rectangle * pConstRect = new Rectangle;
    Rectangle * const pConstPtr = new Rectangle;
 
    cout << "pRect width: " << pRect->GetWidth() 
       << " feet"  << endl;
    cout << "pConstRect width: " << pConstRect->GetWidth() 
       << " feet" << endl;
    cout << "pConstPtr width: " << pConstPtr->GetWidth() 
       << " feet" << endl;
 
    pRect->SetWidth(10);
    // pConstRect->SetWidth(10);
    pConstPtr->SetWidth(10);
 
    cout << "pRect width: " << pRect->GetWidth() 
       << " feet\n";
    cout << "pConstRect width: " << pConstRect->GetWidth() 
       << " feet\n";
    cout << "pConstPtr width: " << pConstPtr->GetWidth() 
       << " feet\n";
    return 0;
}

⌨️ 快捷键说明

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