自己封装一个矩形类(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);void set_w(int w);void set_h(int h);void show();
};void Rect::init(int w,int h)
{Rect::width = w;this->height = h;
}void Rect::set_w(int w)
{this->width = w;
}void Rect::set_h(int h)
{Rect::height = h;
}void Rect::show()
{cout << "周长为:" << (this->width + this->height)*2 << endl;cout << "面积为:" << this->width * this->height << endl;
}
int main()
{Rect rectangle;rectangle.init(1,1);int w,h;cout << "请输入矩形宽度:" << endl;cin >> w;cout << "请输入矩形高度:" << endl;cin >> h;rectangle.set_w(w);rectangle.set_h(h);rectangle.show();return 0;
}
思维导图