编写一个矩形类,数据成员为长和宽,成员函数包括计算周长函数,计算面积函数,构造函数,析构函数,在主函数中定义矩形类对象,计算并输出其面积
时间: 2023-04-01 21:00:18 浏览: 185
好的,这是一个关于编程的问题。矩形类的定义如下:
class Rectangle {
private:
double length;
double width;
public:
Rectangle(double l, double w) {
length = l;
width = w;
}
~Rectangle() {}
double perimeter() {
return 2 * (length + width);
}
double area() {
return length * width;
}
};
在主函数中,我们可以定义一个矩形对象,并计算其面积:
int main() {
Rectangle rect(3, 4);
cout << "The area of the rectangle is: " << rect.area() << endl;
return ;
}
输出结果为:
The area of the rectangle is: 12
相关问题
用C++编写一个程序,编写一个矩形类,数据成员为长和宽,成员函数包括计算周长函数、计算面积函数、构造函数。由矩形类派生出一个正方形类,成员函数包括构造函数、析构函数等。在主函数中定义正方形类对象,计算并输出其周长和面积
好的,下面是我为您编写的代码:
#include <iostream>
using namespace std;
// 矩形类
class Rectangle {
protected:
double length; // 长
double width; // 宽
public:
Rectangle(double l, double w) {
length = l;
width = w;
}
double getPerimeter() { // 计算周长
return 2 * (length + width);
}
double getArea() { // 计算面积
return length * width;
}
};
// 正方形类
class Square : public Rectangle {
public:
Square(double s) : Rectangle(s, s) {} // 构造函数
~Square() {} // 析构函数
};
int main() {
Square s(5); // 定义正方形对象
cout << "正方形的周长为 " << s.getPerimeter() << endl;
cout << "正方形的面积为 " << s.getArea() << endl;
return 0;
}
这个程序定义了一个矩形类 Rectangle
,并在其中定义了构造函数、计算周长和面积的成员函数。然后,通过 Square
类继承了 Rectangle
类,并重载了构造函数,以实现正方形对象的创建。在主函数中,定义了一个正方形对象 s
,并调用其成员函数计算并输出周长和面积。
希望这个程序能够帮到您,如果您有任何问题,请随时问我。
用C++编写一个程序,编写一个矩形类,数据成员包括长和宽,成员函数包括积算周长函数、计算面积函数、构造函数。由矩形类派生出一个正方形类,成员函数包括构造函数、析构函数等。在主函数中定义正方形类对象,计算并输出其周长和面积
好的,下面是我为您编写的代码:
#include <iostream>
using namespace std;
// 矩形类
class Rectangle {
protected:
double length; // 长
double width; // 宽
public:
Rectangle(double l, double w) {
length = l;
width = w;
}
double getPerimeter() { // 计算周长
return 2 * (length + width);
}
double getArea() { // 计算面积
return length * width;
}
};
// 正方形类
class Square : public Rectangle {
public:
Square(double s) : Rectangle(s, s) {} // 构造函数
~Square() {} // 析构函数
};
int main() {
Square s(5); // 定义正方形对象
cout << "正方形的周长为 " << s.getPerimeter() << endl;
cout << "正方形的面积为 " << s.getArea() << endl;
return 0;
}
这个程序定义了一个矩形类 Rectangle
,并在其中定义了构造函数、计算周长和面积的成员函数。然后,通过 Square
类继承了 Rectangle
类,并重载了构造函数,以实现正方形对象的创建。在主函数中,定义了一个正方形对象 s
,并调用其成员函数计算并输出周长和面积。
希望这个程序能够帮到您,如果您有任何问题,请随时问我。
相关推荐











