作业要求:
程序代码:
#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() //输出矩形的周长和面积的函数
{
cout << "周长是:" << 2*(height+width) << endl << "面积是:" << width*height << endl;
}
};
int main()
{
Rect rect;
cout << "请输入矩形的宽和高:" ;
int w,h;
cin >> w >> h;
rect.init(w,h); //输入初始矩形数据
rect.show(); //输出初始矩形数据
cout << "修改后的矩形的宽和高:" ;
cin >> w >> h;
rect.set_h(h); //修改矩形高
rect.set_w(w); //修改矩形宽
rect.show(); //输出修改后矩形信息
return 0;
}
运行结果:
课程总结: