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

运行结果:

思维导图:

相关推荐
_Twink1e16 分钟前
[算法竞赛]九、C++标准模板库STL常用容器大全
开发语言·c++
永恒_顺其自然27 分钟前
Java Web 传统项目异步分块上传系统实现方案
java·开发语言·前端
bu_shuo43 分钟前
c++中对数组求和
开发语言·c++
赫瑞43 分钟前
Java中的大数处理 —— BigInteger
java·开发语言
r_oo_ki_e_44 分钟前
java25--Collection集合
java·开发语言
elseif1231 小时前
【Markdown】指南(上)
linux·开发语言·前端·javascript·c++·笔记
星辰徐哥1 小时前
C++网络编程:TCP服务器与客户端的实现
网络·c++·tcp/ip
初九之潜龙勿用1 小时前
C# 解决“因为算法不同,客户端和服务器无法通信”的问题
服务器·开发语言·网络协议·网络安全·c#
不知名。。。。。。。。1 小时前
Qt常用控件
开发语言·qt
顾温1 小时前
数据转换函数
开发语言·算法