类成员函数,计算矩形周长
时间: 2023-09-30 12:05:26 浏览: 54
好的,我可以为您写一个计算矩形周长的类成员函数。以下是一个示例代码:
```c++
class Rectangle {
private:
double length, width;
public:
Rectangle(double l, double w) {
length = l;
width = w;
}
double perimeter() {
return 2 * (length + width);
}
};
```
在上面的代码中,我们定义了一个名为 `Rectangle` 的类,它有两个私有成员变量 `length` 和 `width`,以及一个公有成员函数 `perimeter`,用于计算矩形的周长。在构造函数中,我们将矩形的长度和宽度传递给类,并在 `perimeter` 函数中使用这些值来计算矩形的周长。如果您想要计算矩形的周长,只需创建一个 `Rectangle` 对象并调用 `perimeter` 函数即可。
相关问题
用C++编写一个程序,编写一个矩形类,数据成员为长和宽,成员函数包括计算周长函数、计算面积函数、构造函数。由矩形类派生出一个正方形类,成员函数包括构造函数、析构函数等。在主函数中定义正方形类对象,计算并输出其周长和面积
好的,下面是我为您编写的代码:
```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`,并调用其成员函数计算并输出周长和面积。
希望这个程序能够帮到您,如果您有任何问题,请随时问我。
编写一个矩形类,数据成员为长和宽,成员函数包括计算周长函数,计算面积函数,构造函数,析构函数,在主函数中定义矩形类对象,计算并输出其面积
好的,这是一个关于编程的问题。矩形类的定义如下:
```
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
```