/************
./header/class.hpp
************/
- #include
- using namespace std;
- /**
- * 例1:一个初级的矩形类
- */
- class Rectangle {
- public:
- // 声明Rectangle的构造函数
- Rectangle(int width, int height);
- // 声明并定义Rectangle的析构函数
- ~Rectangle() {};
- // 声明并定义Rectangle的获取高度的函数
- int GetHeight() const {return itsHeight;}
- // 声明并定义Rectangle的一个获取宽度的函数
- int GetWidth() const {return itsWidth;}
- // 声明并定义Rectangle的一个获取面积的函数
- int GetArea() const {return itsHeight * itsWidth;}
- // 声明并定义Rectangle的一个计算周长的函数
- int GetPerim() const {return 2 * itsHeight + 2 * itsWidth;}
- // 声明Rectangle的一个设置宽高的函数
- void SetSize(int newWidth, int newHeight);
- private:
- int itsWidth;
- int itsHeight;
- };
- // 定义Rectangle的设置宽高的函数
- void Rectangle::SetSize(int newWidth, int newHeight) {
- itsWidth = newWidth;
- itsHeight = newHeight;
- }
- // 定义Rectangle的构造函数
- Rectangle::Rectangle(int width, int height) {
- itsWidth = width;
- itsHeight = height;
- }
- // 申明输出菜单的函数
- int DoMenu();
- // 声明绘制矩形的函数
- void DoDrawRect(Rectangle);
- // 声明获取面积的函数
- void DoGetArea(Rectangle);
- // 声明计算周长的函数
- void DoGetPerim(Rectangle);
/************
./src/test1.hpp
************/
- #include ../header/class.hpp
- // 定义一个枚举,由1开始
- enum CHOICE {
- DrawRect = 1,
- GetArea,
- GetPerim,
- ChangeDimensions,
- Quit
- };
- int main() {
- // 创建一个矩形类
- Rectangle theRect(30, 5);
- // 声明默认的选择
- int choice = DrawRect;
- // 声明退出
- bool fQuit = false;
- while (!fQuit) {
- // 执行选择
- choice = DoMenu();
- // 如果选择的结果超过可选范围,则跳过
- if (choice < DrawRect || choice > Quit) {
- cout << \nInvalid Choice, try again.;
- cout << endl << endl;
- continue;
- }
- // 判断输入的数据
- switch(choice) {
- case DrawRect:
- DoDrawRect(theRect);
- break;
- case GetArea:
- DoGetArea(theRect);
- break;
- case GetPerim:
- DoGetPerim(theRect);
- break;
- case ChangeDimensions:
- int newLength, newWidth;
- cout << \nNew width:;
- cin >> newWidth;
- cout << \nNew height:;
- cin >> newLength;
- theRect.SetSize(newWidth, newLength);
- DoDrawRect(theRect);
- break;
- case Quit:
- fQuit = true;
- cout << \nExiting.. << endl << endl;
- break;
- default:
- cout << \nError in choice << endl;
- fQuit = true;
- break;
- }
- }
- return 0;
- }
- // 定义输出菜单的函数
- int DoMenu() {
- int choice;
- cout << endl << endl;
- cout << *** Menu *** << endl;
- cout << (1) Draw Rectangle << endl;
- cout << (2) Area << endl;
- cout << (3) Perimeter << endl;
- cout << (4) Resize << endl;
- cout << (5) Quit << endl;
- cin >> choice;
- return choice;
- }
- // 定义绘制矩形的函数
- void DoDrawRect(Rectangle theRect) {
- int height = theRect.GetHeight();
- int width = theRect.GetWidth();
- int i, j;
- for (i = 0; i < height; i++) {
- for (j = 0; j < width; j++) {
- cout << *;
- }
- cout << endl;
- }
- }
- void DoGetArea(Rectangle theRect) {
- cout << Area: << theRect.GetArea() << endl;
- }
- void DoGetPerim(Rectangle theRect) {
- cout << Perimeter: << theRect.GetPerim() << endl;
- }
转载于:https://blog.51cto.com/machine/428319