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

运行结果:

思维导图:

相关推荐
黄焖鸡能干四碗12 分钟前
固定资产管理系统(蓝牙标签打印+移动端Java+Vue+Uniapp源码)
java·开发语言·vue.js·eclipse·uni-app
我好喜欢你~32 分钟前
C#---共享项目
开发语言·c#
丨 丨34 分钟前
Python 爬虫基础教学
开发语言·爬虫·python
烟雨迷43 分钟前
web自动化测试(selenium)
运维·开发语言·前端·python·selenium·测试工具
潼心1412o2 小时前
C语言(长期更新)第12讲:指针二详解
c语言·开发语言
荼蘼2 小时前
Python 爬虫实战:爬取 B 站视频的完整教程
开发语言·爬虫·python
小菜全3 小时前
使用Java获取本地PDF文件并解析数据
java·开发语言·python
chinesegf3 小时前
浏览器内存 (JavaScript运行时内存)存储的优劣分析
开发语言·javascript·ecmascript
yangchanghua1113 小时前
Caused by: java.net.SocketTimeoutException: Read timed out;
java·开发语言·spring
无边风月-风之羽翼3 小时前
【自记录】Ubuntu20.04下Python自编译
开发语言·python