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

运行结果:

思维导图:

相关推荐
困死,根本不会3 小时前
Kivy+Buildozer 打包 APK 踩坑:python-for-android 克隆失败
开发语言·php·kivy
咸鱼2.05 小时前
【java入门到放弃】跨域
java·开发语言
skiy5 小时前
java与mysql连接 使用mysql-connector-java连接msql
java·开发语言·mysql
一念春风5 小时前
智能文字识别工具(AI)
开发语言·c#·wpf
桦06 小时前
【C++复习】:继承
开发语言·c++
何仙鸟6 小时前
GarmageSet下载和处理
java·开发语言
鱼难终6 小时前
类和对象(下)
c++
wefly20176 小时前
免安装!m3u8live.cn在线 M3U8 播放器,小白也能快速上手
java·开发语言·python·json·php·m3u8·m3u8在线转换
云泽8087 小时前
深入 AVL 树:原理剖析、旋转算法与性能评估
数据结构·c++·算法
薛先生_0997 小时前
js学习语法第一天
开发语言·javascript·学习