作业:
自己封装一个矩形类(Rect),拥有私有属性:宽度(width)、高度(height),
定义公有成员函数:
初始化函数:void init(int w, int h)
更改宽度的函数:set_w(int w)
更改高度的函数:set_h(int h)
输出该矩形的周长和面积函数:void show()
rect.h
#ifndef RECT_H
#define RECT_H#include <iostream>
using namespace std;class Rect
{
private:int h;int w;
public:void init(int h,int w);void set_h(int h);void set_w(int w);void show();};#endif // RECT_H
test.cpp
#include "rect.h"void Rect::init(int h,int w)
{this->h = h;this->w = w;
}
void Rect::set_h(int h)
{this->h = h;
}
void Rect::set_w(int w)
{this->w = w;
}
void Rect::show()
{cout << "len = " << (h+w)*2 << endl;cout << "aer = " << h*w << endl;
}
main.cpp
#include "rect.h"int main()
{int h , w;char a;Rect j1;cout << "请输入长和宽:" ;cin >> h >> w;j1.init(h,w);j1.show();cout << "是否修改长度y/n:" ;cin >> a;if(a == 'y' || a == 'Y'){cout << "请输入新的长度:";cin >> h;j1.set_h(h);j1.show();}cout << "是否修改宽度y/n:" ;cin >> a;if(a == 'y' || a == 'Y'){cout << "请输入新的宽度:";cin >> w;j1.set_w(w);j1.show();}return 0;
}
运行结果示意图
思维导图