设计一个矩形类Rectangle,私有数据成员包括整型数据:length(长),width(宽)。 公共成员函数为: (1)input,输入length,width 友元非类的普通函数为: (1)display,输出length,width main函数中创建Rectangle对象,调用对象的input函数,然后调用display函数显示对象的私有成员。 【输入形式】 整数长 整数宽 【输出形式】 整数长 整数宽 【样例输入】 3 5 【样例输出】 3 5用C++写
时间: 2024-02-19 08:57:30 浏览: 30
以下是C++代码实现:
```cpp
#include <iostream>
using namespace std;
class Rectangle {
private:
int length; // 长
int width; // 宽
public:
void input(int l, int w) {
length = l;
width = w;
}
friend void display(Rectangle rect);
};
void display(Rectangle rect) {
cout << rect.length << " " << rect.width << endl;
}
int main() {
int l, w;
cin >> l >> w;
Rectangle rect;
rect.input(l, w);
display(rect);
return 0;
}
```
运行结果:
输入:
```
3 5
```
输出:
```
3 5
```
相关问题
定义一个描述矩形的类Rectangle,包括: •数据成员有宽(width)和长 (length);
好的,以下是一个描述矩形的类Rectangle的示例代码,包括宽(width)和长 (length)两个数据成员:
```python
class Rectangle:
def __init__(self, width, length):
self.width = width
self.length = length
def area(self):
return self.width * self.length
def perimeter(self):
return 2 * (self.width + self.length)
```
这个类包括一个初始化方法 `__init__`,用于创建一个新的矩形对象并指定其宽度和长度。还包括两个方法:`area`用于计算矩形的面积,`perimeter`用于计算矩形的周长。可以通过以下代码来测试这个类:
```python
rect = Rectangle(5, 10)
print("矩形的面积为:", rect.area())
print("矩形的周长为:", rect.perimeter())
```
输出结果为:
```
矩形的面积为: 50
矩形的周长为: 30
```
设计一个矩形类Rectangle 数据成员: length(私有),width(私有)和color(公有) 成员函数:(均为公有) SetLengthWidth,GetLengthWi GetArea, ShowColor,SetColor 并设计一个主函数来测试你所编写的类。
```c++
#include <iostream>
using namespace std;
class Rectangle {
private:
double length;
double width;
public:
string color;
void SetLengthWidth(double l, double w) {
length = l;
width = w;
}
double GetLength() {
return length;
}
double GetWidth() {
return width;
}
double GetArea() {
return length * width;
}
void ShowColor() {
cout << "Color: " << color << endl;
}
void SetColor(string c) {
color = c;
}
};
int main() {
Rectangle rect;
rect.SetLengthWidth(4.5, 3.2);
rect.SetColor("red");
rect.ShowColor();
cout << "Length: " << rect.GetLength() << endl;
cout << "Width: " << rect.GetWidth() << endl;
cout << "Area: " << rect.GetArea() << endl;
return 0;
}
```