C++作业2

自己封装一个矩形类(Rect),拥有私有属性:宽度(width)、高度(height),

定义公有成员函数:

初始化函数:void init(int w, int h)

更改宽度的函数:set_w(int w)

更改高度的函数:set_h(int h)

输出该矩形的周长和面积函数:void show()

代码:

cpp 复制代码
#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)
{
    this->width = w;
    this->height = h;
}

void Rect::set_w(int w)
{
    this->width = w;
}

void Rect::set_h(int h)
{
    this->height = h;
}

void Rect::show()
{
    cout << "周长为:" << width+height << endl;
    cout << "面积为:" << width*height << endl;
}

int main()
{
    int height,width;
    Rect s1;
    s1.init(5,10);
    cout << "初始的周长和面积:" << endl;
    s1.show();
    cout << "请输入要更改的长和宽:";
    cin >> height >> width;
    s1.set_h(height);
    s1.set_w(width);
    s1.show();
    return 0;
}

运行结果:

思维导图:

相关推荐
小c君tt21 分钟前
QT中想在QTextEdit控件中使用Qslog日志输出出现问题原因及解决方法
开发语言·qt
王老师青少年编程1 小时前
csp信奥赛C++标准模板库STL案例应用5
c++·stl·set·集合·标准模板库·csp·信奥赛
历程里程碑1 小时前
hot 206
java·开发语言·数据结构·c++·python·算法·排序算法
csbysj20201 小时前
菜单(Menu)
开发语言
Tipriest_1 小时前
C++ 的 ranges 和 Python 的 bisect 在二分查找中的应用与实现
c++·python·算法·二分法
誰能久伴不乏2 小时前
epoll 学习踩坑:`fcntl` 设置非阻塞到底用 `F_SETFL` 还是 `F_SETFD`?
linux·服务器·网络·c++·tcp/ip
yong99902 小时前
基于MATLAB的随机振动界面设计与功率谱密度分析实现
开发语言·matlab
超级种码2 小时前
Java:JavaAgent技术(java.instrument和java.attach)
java·开发语言·python
天天向上10242 小时前
go 配置热更新
开发语言·后端·golang
杨忆2 小时前
构建自己的开发工作台MFC
数据库·c++·mfc