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;
}

运行结果:

思维导图:

相关推荐
方也_arkling12 分钟前
【八股】JS中的事件循环
开发语言·前端·javascript·ecmascript
你怎么知道我是队长17 分钟前
C语言---函数指针和回调函数
c语言·开发语言
坚持学习前端日记17 分钟前
原生Android开发与JS桥开发对比分析
android·开发语言·javascript
jiunian_cn20 分钟前
【C++11】C++11重要新特性详解
开发语言·c++
何中应24 分钟前
windows安装python环境
开发语言·windows·python
tbRNA33 分钟前
C/C++ 内存管理
c语言·c++
zh_xuan36 分钟前
kotlin 测试if表达式、数组等
开发语言·kotlin
问道飞鱼36 分钟前
【Rust编程】Cargo 工具详解:从基础到高级的完整指南
开发语言·后端·rust·cargo
zhaokuner39 分钟前
14-有界上下文-DDD领域驱动设计
java·开发语言·设计模式·架构
WBluuue1 小时前
AtCoder Beginner Contest 438(ABCDEF)
c++·算法