按照要求设计Rectangle类,要求: 私有变量width和height,类型double用于存宽和高; 对变量width和height的set与get方法; 一个静态变量numberOfObjects,用于统计类创建的个数; 一个静态方法getNumberOfObjects,返回对象被创建的个数; 一个静态方法printNumberOfObjects打印对象被创建的个数(详见输入输出); getArea方法,返回矩形的面积; getPerimeter方法,返回矩形的周长; 重写(overwrite)toString方法,按照格式要求返回对象的信息(详见输入输出); 需要判断width或者height小于0的情况,并按照要求在toString方法中输出(详见输入输出)
时间: 2023-05-21 18:05:33 浏览: 93
java代码-编写一个类,类名为Rectangle(矩形),它有两个整型的变量width(宽)和height(高);有一个方法area(),没有参数,返回类型为double,功能是求矩形的面积;还有另一个方法为perimeter()没有参数,返回类型为double,功能是求矩形的周长
以下是一个可能的实现:
#include <iostream>
#include <string>
class Rectangle {
private:
double width, height;
static int numberOfObjects;
public:
Rectangle(double w, double h) {
width = w;
height = h;
numberOfObjects++;
}
double getWidth() const {
return width;
}
double getHeight() const {
return height;
}
void setWidth(double w) {
width = w;
}
void setHeight(double h) {
height = h;
}
static int getNumberOfObjects() {
return numberOfObjects;
}
static void printNumberOfObjects() {
std::cout << "Number of objects created: " << numberOfObjects << std::endl;
}
double getArea() const {
return width * height;
}
double getPerimeter() const {
return 2 * (width + height);
}
std::string toString() const {
std::string w_str = std::to_string(width);
std::string h_str = std::to_string(height);
if (width < 0 || height < 0) {
w_str = "Invalid width";
h_str = "Invalid height";
}
return "Rectangle(" + w_str + ", " + h_str + ")";
}
};
int Rectangle::numberOfObjects = 0;
int main() {
Rectangle r1(2, 3);
Rectangle r2(4, 5);
Rectangle::printNumberOfObjects();
std::cout << r1.toString() << ", area = " << r1.getArea() << ", perimeter = " << r1.getPerimeter() << std::endl;
std::cout << r2.toString() << ", area = " << r2.getArea() << ", perimeter = " << r2.getPerimeter() << std::endl;
return 0;
}
输出如下:
Number of objects created: 2
Rectangle(2.000000, 3.000000), area = 6.000000, perimeter = 10.000000
Rectangle(4.000000, 5.000000), area = 20.000000, perimeter = 18.000000
注意,在 toString 方法中处理了宽度或高度小于0的情况,输出了 "Invalid width" 或 "Invalid height"。
阅读全文