定义描述矩形的类 Rectangle,其私有数据成员为矩形的长(Length)与宽(Width),其公有函数成员为构造函数、计算矩形面积的函数 Area()与输出矩形长、宽和面积的函数 Display()。在主函数中用矩形类定义矩形对象 rct,并赋初始值(40,30),最后显示矩形的长、宽与面积
#include <iostream>
class Rectangle {
private:
int length_;
int width_;
public:
// Constructor
Rectangle(int length, int width) : length_(length), width_(width) {}
// Member function to calculate the area of the rectangle
int Area() { return length_ * width_; }
// Member function to display the length, width, and area of the rectangle
void Display() {
std::cout << "Length: " << length_ << std::endl;
std::cout << "Width: " << width_ << std::endl;
std::cout << "Area: " << Area() << std::endl;
}
};
int main() {
// Create a rectangle object with length 40 and width 30
Rectangle rct(40, 30);
// Display the length, width, and area of the rectangle
rct.Display();
return 0;
}
仅供参考,望采纳,谢谢。
#include <iostream>
using namespace std;
class Rectangle
{
private:
float Length, Width;
public:
Rectangle(float l = 0, float w = 0) : Length(l), Width(w){};
float Area() { return Length * Width; };
void Display()
{
cout << Length << " " << Width << " " << Area() << endl;
};
};
int main()
{
Rectangle rct(40, 30);
rct.Display();
return 0;
}