C++ 实现点类和矩形类:计算矩形面积并输出坐标
以下是使用C++编写的Point和Rectangle类的示例代码:\n\ncpp\n#include <iostream>\nusing namespace std;\n\nclass Point {\nprivate:\n int x;\n int y;\npublic:\n Point(int x, int y) {\n this->x = x;\n this->y = y;\n }\n \n int getX() {\n return x;\n }\n \n int getY() {\n return y;\n }\n};\n\nclass Rectangle {\nprivate:\n Point topLeft;\n Point bottomRight;\npublic:\n Rectangle(Point topLeft, Point bottomRight) {\n this->topLeft = topLeft;\n this->bottomRight = bottomRight;\n }\n \n int getTopLeftX() {\n return topLeft.getX();\n }\n \n int getTopLeftY() {\n return topLeft.getY();\n }\n \n int getBottomRightX() {\n return bottomRight.getX();\n }\n \n int getBottomRightY() {\n return bottomRight.getY();\n }\n \n int getArea() {\n int width = bottomRight.getX() - topLeft.getX();\n int height = bottomRight.getY() - topLeft.getY();\n return width * height;\n }\n};\n\nint main() {\n Point p1(1, 3);\n Point p2(5, 1);\n \n Rectangle rect(p1, p2);\n \n cout << "Top left: (" << rect.getTopLeftX() << ", " << rect.getTopLeftY() << ")" << endl;\n cout << "Bottom right: (" << rect.getBottomRightX() << ", " << rect.getBottomRightY() << ")" << endl;\n cout << "Area: " << rect.getArea() << endl;\n \n return 0;\n}\n\n\n运行此程序将输出以下结果:\n\n\nTop left: (1, 3)\nBottom right: (5, 1)\nArea: 8\n\n\n这表示我们创建了一个以(1, 3)和(5, 1)为对角顶点的矩形,并且其面积为8。
原文地址: https://www.cveoy.top/t/topic/qbZZ 著作权归作者所有。请勿转载和采集!