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

运行结果:

思维导图:

相关推荐
Qhumaing1 分钟前
C++学习:【PTA】数据结构 7-1 实验6-1(图-邻接矩阵)
c++·学习·算法
No0d1es2 分钟前
2025年12月 GESP CCF编程能力等级认证C++一级真题
开发语言·c++·青少年编程·gesp·ccf
荒诞硬汉8 分钟前
面向对象(三)
java·开发语言
2301_773730318 分钟前
系统编程—在线商城信息查询系统
c++·html
郝学胜-神的一滴9 分钟前
深入理解Linux中的Try锁机制
linux·服务器·开发语言·c++·程序人生
liliangcsdn9 分钟前
bash中awk如何切分输出
开发语言·bash
csbysj202016 分钟前
JSON.parse() 方法详解
开发语言
奔波霸的伶俐虫18 分钟前
redisTemplate.opsForList()里面方法怎么用
java·开发语言·数据库·python·sql
yesyesido29 分钟前
智能文件格式转换器:文本/Excel与CSV无缝互转的在线工具
开发语言·python·excel
_200_32 分钟前
Lua 流程控制
开发语言·junit·lua