自己封装一个矩形类(Rect),拥有私有属性:宽度(width)、高度(height),
定义公有成员函数:
初始化函数:void init(int w, int h)
更改宽度的函数:set_w(int w)
更改高度的函数:set_h(int h)
输出该矩形的周长和
#include <iostream>
using namespace std;
//封装一个矩形类(Rect)
//拥有私有属性:宽度(wide)、高度(hight)
//定义成员函数:初始化函数、更改宽度的函数、更改高度的函数、输出矩形周长和面积的函数
class Rect
{
private:
int wide;
int hight;
public:
void init(int w,int h)
{
wide = w;
hight = h;
}
void ch_wide()
{
cout << "请输入宽度" << endl;
cin >> wide ;
}
void ch_hight()
{
cout << "请输入高度" << endl;
cin >> hight;
}
void show()
{
cout << "周长: " << ((wide*2)+hight*2) << endl;
cout << "面积: " << (wide*hight) <<endl;
}
};
int main()
{
Rect rec;
int w;
int h;
cout << "请输入宽度: " << endl;
cin >> w;
cout << "请输入高度: " << endl;
cin >> h;
rec.init(w,h);
while(1)
{
system("CLS");
rec.show();
cout << "按1进行计算矩形周长与面积" << endl;
cout << "按0退出" << endl;
int key;
cout << "请输入选项" << endl;
cin >> key ;
switch (key)
{
case 0:
{
goto END;
}
break;
case 1:
{
rec.ch_wide();
rec.ch_hight();
rec.show();
}
break;
}
}
END:
cout << "退出成功" << endl;
return 0;
}
面积函数:void show()