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

运行结果:

思维导图:

相关推荐
zzywxc78716 分钟前
AI 正在深度重构软件开发的底层逻辑和全生命周期,从技术演进、流程重构和未来趋势三个维度进行系统性分析
java·大数据·开发语言·人工智能·spring
江理不变情35 分钟前
图像质量对比感悟
c++·人工智能
灵性花火36 分钟前
Qt的前端和后端过于耦合(0/7)
开发语言·前端·qt
DES 仿真实践家1 小时前
【Day 11-N22】Python类(3)——Python的继承性、多继承、方法重写
开发语言·笔记·python
apocelipes2 小时前
记一次ADL导致的C++代码编译错误
c++·开发工具和环境
Code Warrior2 小时前
【每日算法】专题五_位运算
开发语言·c++
沐知全栈开发5 小时前
HTML DOM 访问
开发语言
脑袋大大的6 小时前
JavaScript 性能优化实战:减少 DOM 操作引发的重排与重绘
开发语言·javascript·性能优化
二进制person7 小时前
Java SE--方法的使用
java·开发语言·算法
OneQ6667 小时前
C++讲解---创建日期类
开发语言·c++·算法