📄 hour10_1.cpp
字号:
// 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 + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -