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

运行结果:

思维导图:

相关推荐
Whisper_Sy12 分钟前
Flutter for OpenHarmony移动数据使用监管助手App实战 - 应用列表实现
android·开发语言·javascript·flutter·php
小CC吃豆子17 分钟前
Python爬虫
开发语言·python
机器视觉知识推荐、就业指导21 分钟前
Qt 6 所有 QML 类型(官方完整清单 · 原始索引版)
开发语言·qt
jojo_zjx1 小时前
GESP 24年12月2级 数位和
c++
自由的好好干活1 小时前
PCI9x5x驱动移植支持PCI9054在win7下使用3
c++·驱动开发
techdashen1 小时前
Rust OnceCell 深度解析:延迟初始化的优雅解决方案
开发语言·oracle·rust
少控科技1 小时前
QT新手日记033
开发语言·qt
王九思1 小时前
Java 内存分析工具 MAT
java·开发语言·安全
superman超哥2 小时前
Serde 的零成本抽象设计:深入理解 Rust 序列化框架的哲学
开发语言·rust·开发工具·编程语言·rust序列化
夕除2 小时前
java--2
java·开发语言