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

运行结果:

思维导图:

相关推荐
W.A委员会7 小时前
JS原型链详解
开发语言·javascript·原型模式
止语Lab7 小时前
Go并发编程实战:Channel 还是 Mutex?一个场景驱动的选择框架
开发语言·后端·golang
她说彩礼65万7 小时前
C# 实现简单的日志打印
开发语言·javascript·c#
绿浪19847 小时前
c# 中结构体 的定义字符串字段(性能优化)
开发语言·c#
房开民8 小时前
可变参数模板
java·开发语言·算法
t***5448 小时前
如何在现代C++中更有效地应用这些模式
java·开发语言·c++
itman3019 小时前
C语言、C++与C#深度研究:从底层到现代开发演进全解析
c语言·c++·c·内存管理·编译模型
Victoria.a9 小时前
python基础语法
开发语言·python
xiaoyaohou1110 小时前
023、数据增强改进(二):自适应数据增强与AutoAugment策略
开发语言·python
鬼圣10 小时前
Python 上下文管理器
开发语言·python