#include using namespace std;

class Rectangle { private: double width; double height;

public: // 默认构造函数 Rectangle() { width = 0; height = 0; }

// 带参数的构造函数
Rectangle(double w, double h) {
    width = w;
    height = h;
}

// 获取宽度
double GetWidth() {
    return width;
}

// 获取高度
double GetHeight() {
    return height;
}

// 设置宽度和高度
void Set(double w, double h) {
    width = w;
    height = h;
}

// 计算周长
double Perimeter() {
    return 2 * (width + height);
}

// 计算面积
double Area() {
    return width * height;
}

};

int main() { Rectangle rect1; cout'Show object rect1:'<<endl; cout' width='<<rect1.GetWidth()<<endl; cout' height='<<rect1.GetHeight()<<endl; cout' Perimeter='<<rect1.Perimeter()<<endl; cout' Area='<<rect1.Area()<<endl; double w,h; cin>>w>>h; Rectangle rect2(w,h); cout'Show object rect2:'<<endl; cout' width='<<rect2.GetWidth()<<endl; cout' height='<<rect2.GetHeight()<<endl; cout' Perimeter='<<rect2.Perimeter()<<endl; cout' Area='<<rect2.Area()<<endl; cin>>w>>h; cout'Reset and Show object rect1:'<<endl; rect1.Set(w,h); cout' width='<<rect1.GetWidth()<<endl; cout' height='<<rect1.GetHeight()<<endl; cout' Perimeter='<<rect1.Perimeter()<<endl; cout' Area='<<rect1.Area()<<endl; return 0; }

C++ 设计矩形类 Rectangle:实现构造函数、获取和设置方法以及计算周长和面积

原文地址: https://www.cveoy.top/t/topic/oyOV 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录