constptr.cpp

来自「24学时攻克C++光盘源代码 深入浅出 方便实用」· C++ 代码 · 共 53 行

CPP
53
字号
 // 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);
     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 + -
显示快捷键?