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

运行结果:

思维导图:

相关推荐
一个天蝎座 白勺 程序猿10 分钟前
KingbaseES查询逻辑优化深度解析:从子查询到语义优化的全链路实践
开发语言·数据库·kingbasees·金仓数据库
skywalker_111 小时前
Java中异常
java·开发语言·异常
2501_940315261 小时前
航电oj:首字母变大写
开发语言·c++·算法
没有天赋那就反复1 小时前
JAVA 静态方法
java·开发语言
Thomas_YXQ1 小时前
Unity3D在ios平台下内存的优化详解
开发语言·macos·ios·性能优化·cocoa
lhxcc_fly1 小时前
手撕简易版的智能指针
c++·智能指针实现
咸甜适中1 小时前
rust的docx-rs库,自定义docx模版批量生成docx文档(逐行注释)
开发语言·rust·docx·docx-rs
浒畔居1 小时前
泛型编程与STL设计思想
开发语言·c++·算法
Fcy6481 小时前
C++ 异常详解
开发语言·c++·异常
机器视觉知识推荐、就业指导2 小时前
Qt 和 C++,是不是应该叫 Q++ 了?
开发语言·c++·qt