作业:
自己封装一个矩形类(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:
double width;
double height;
public:
void init(double w,double h);
void set_w(double w);
void set_h(double h);
void show();
};
void Rect::init(double w,double h){
this->width = w;
this->height = h;
}
void Rect::set_w(double w){
this->width = w;
cout << "更改后的宽为:" << w << endl;
}
void Rect::set_h(double h){
this->height = h;
cout << "更改后的长为:" << h << endl;
}
void Rect::show(){
cout << "矩形的周长为:" << (width+height)*2 << endl;
cout << "矩形的面积为:" << width*height << endl;
}
int main()
{
Rect r1;
r1.init(3,4);
r1.show();
r1.set_w(4);
r1.set_h(5);
return 0;
}
运行结果:
思维导图: