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

运行结果:

思维导图:

相关推荐
Rabitebla1 天前
【数据结构】实现通讯录:基于C语言动态顺序表
c语言·开发语言·数据结构·算法
tankeven1 天前
动态规划专题(06):树形动态规划(未完待续)
c++·算法·动态规划
满天星83035771 天前
【Linux/多路复用】poll和epoll的使用
linux·服务器·c++·后端
覆东流1 天前
第6天:python综合练习——制作简易计算器
开发语言·后端·python
waves浪游1 天前
进程间通信(上)
linux·运维·服务器·开发语言·c++
圆弧YH1 天前
Python→ Bookmark
开发语言·python
hhb_6181 天前
C Shell脚本编程与系统管理技术实践指南
java·c语言·开发语言
wjs20241 天前
Rust 循环
开发语言
小雅痞1 天前
[Java][Leetcode hard] 68. 文本左右对齐
java·开发语言·leetcode
棋子入局1 天前
C语言制作消消乐游戏(3)
c语言·开发语言·游戏