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

运行结果:

思维导图:

相关推荐
Ulyanov10 分钟前
高保真单脉冲雷达导引头回波生成:Python建模与实践
开发语言·python·仿真·系统设计·单脉冲雷达
Mr_WangAndy1 小时前
C++数据结构与算法_线性表_数组_概念动态数组,刷题
c++·二分查找·数组刷题·数组字符串逆序·零移动·有序数组的平方
阿猿收手吧!1 小时前
【C++】jthread:优雅终止线程新方案
开发语言·c++
lly2024061 小时前
《JavaScript 实例》
开发语言
十五年专注C++开发1 小时前
C++中各平台表示Debug的宏
开发语言·c++·debug
张小凡vip1 小时前
Python异步编程实战:基于async/await的高并发实现
开发语言·python
玩c#的小杜同学2 小时前
源代码保卫战:给C# 程序(混淆、加壳与反逆向实战)
开发语言·笔记·c#
阿猿收手吧!3 小时前
【C++】Ranges:彻底改变STL编程方式
开发语言·c++
云游云记3 小时前
php 随机红包数生成
开发语言·php·随机红包
程序员林北北3 小时前
【前端进阶之旅】JavaScript 一些常用的简写技巧
开发语言·前端·javascript