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

运行结果:

思维导图:

相关推荐
南棱笑笑生14 分钟前
20251213给飞凌OK3588-C开发板适配Rockchip原厂的Buildroot【linux-6.1】系统时适配type-C0
linux·c语言·开发语言·rockchip
月屯20 分钟前
Pandoc 之--pdf-engine
java·开发语言·pdf
晨星33427 分钟前
使用 IntelliJ IDEA 轻松连接 Java 与 MySQL 8 数据库
java·开发语言·数据库
古城小栈35 分钟前
Java 在 Web3 时代的新定位
java·开发语言·web3
何中应43 分钟前
【面试题-5】设计模式
java·开发语言·后端·设计模式·面试题
Kiri霧1 小时前
Go包基础与使用指南
开发语言·后端·golang
小猪猪屁1 小时前
顺序表与链表:头插法与尾插法详解
c语言·数据结构·c++
历程里程碑1 小时前
C++ 5:模板初阶
c语言·开发语言·数据结构·c++·算法
‿hhh1 小时前
学习笔记整理(部分)
java·开发语言·笔记·学习·mvc
HappRobot1 小时前
Python 面向对象
开发语言·python