hour10_1.cpp

来自「C++学习的有利助手」· C++ 代码 · 共 58 行

CPP
58
字号
 // Listing 10.5
 // Using pointers with const methods
 #include <iostream>

 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;

     std::cout << "pRect width: "
               << pRect->GetWidth() << " feet" << std::endl;
     std::cout << "pConstRect width: "
               << pConstRect->GetWidth() << " feet" << std::endl;
     std::cout << "pConstPtr width: "
               << pConstPtr->GetWidth() << " feet" << std::endl;

     pRect->SetWidth(10);
     pConstRect->SetWidth(10);

   // You should get a compiler error on the line above -- was commented out in the book.
   // pConstRect is declared to point to a constant Rectangle. 
   // Therefore, it cannot legally call a non-const member function!

     pConstPtr->SetWidth(10);

     std::cout << "pRect width: "
               << pRect->GetWidth() << " feet" << std::endl;
     std::cout << "pConstRect width: "
               << pConstRect->GetWidth() << " feet" << std::endl;
     std::cout << "pConstPtr width: "
               << pConstPtr->GetWidth() << " feet" << std::endl;
     return 0;
 }

⌨️ 快捷键说明

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