封装一个矩形类(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
{
int width;
int height;
public:
void init(int w,int h);
void set_w(int w);
void set_h(int h);
void show();
};
void Rect::set_h(int h)
{
this->height=h;
}
void Rect::set_w(int w)
{
this->width=w;
}
void Rect::init(int w, int h)
{
this->width=w;
this->height=h;
}
void Rect::show()
{
cout << "矩形面积:" << width*height << endl;
}
int main()
{
int w,h;
cin >> w >> h;
Rect r1;
r1.init(w,h);
cout << "初始化成功" << endl;
int a;
while(1)
{
cin >> a;
switch (a) {
case 1:
r1.show();
break;
case 2:
cout << "请输入高度" << endl;
cin >> h;
r1.set_h(h);
break;
case 3:
cout << "请输入宽度" << endl;
cin >> w;
r1.set_w(w);
break;
case 4:
goto END;
}
}
END:
return 0;
}
效果图:
思维导图: