自己封装一个矩形类(Rect),拥有私有属性:宽度(width)、高度(height),
定义公有成员函数:
初始化函数:void init(int w, int h)
更改宽度的函数:set_w(int w)
更改高度的函数:set_h(int h)
输出该矩形的周长和面积函数:void show()
#include <iostream>
using namespace std;
class Rect
{
private: //定义私有属性
int width; //定义宽度
int height ; //定义长度
public: //定义共有函数
//初始化函数
void init(int w,int h)
{
width = w;
height = h;
}
//更改宽度函数
void set_w(int w)
{
width = w;
}
//更改长度函数
void set_h(int h)
{
height = h;
}
//输出函数
void show()
{
int perimeter = 2*(width + height);
int area = width * height;
cout << "perimeter = " << perimeter << endl;
cout << "area = " << area << endl;
}
};
int main()
{
Rect rect;
rect.init(5,10); //初始话矩形长宽
rect.show(); //输出矩形的周长和面积
rect.set_w(8); //修改矩形的宽度
rect.set_h(14); //修改矩形的长度
rect.show(); //输出修改后的矩形的周长和面积
return 0;
}