C++day2——引用、结构体、类

思维导图:

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
{

protected:

private:
    int width;
    int height;
public:
    void init(int w,int h)
    {
        width = w;
        height = h;
    }
    void set_w(int w)
    {
        width = w;
    }
    void set_h(int h)
    {
        height = h;
    }
    void show()
    {
        cout << "周长 = " << 2 * ( width + height ) << endl;
        cout << "面积 = " << width * height << endl;
    }

};

int main()
{
    Rect rec;
    rec.init(3,4);
    rec.show();
    rec.set_h(6);
    rec.show();
    rec.set_w(5);
    rec.show();
    return 0;
}
相关推荐
крон2 小时前
【Auto.js例程】华为备忘录导出到其他手机
开发语言·javascript·智能手机
zh_xuan2 小时前
c++ 单例模式
开发语言·c++·单例模式
老胖闲聊3 小时前
Python Copilot【代码辅助工具】 简介
开发语言·python·copilot
Blossom.1183 小时前
使用Python和Scikit-Learn实现机器学习模型调优
开发语言·人工智能·python·深度学习·目标检测·机器学习·scikit-learn
曹勖之3 小时前
基于ROS2,撰写python脚本,根据给定的舵-桨动力学模型实现动力学更新
开发语言·python·机器人·ros2
豆沙沙包?4 小时前
2025年- H77-Lc185--45.跳跃游戏II(贪心)--Java版
java·开发语言·游戏
军训猫猫头4 小时前
96.如何使用C#实现串口发送? C#例子
开发语言·c#
liuyang-neu4 小时前
java内存模型JMM
java·开发语言
利刃大大5 小时前
【在线五子棋对战】二、websocket && 服务器搭建
服务器·c++·websocket·网络协议·项目
喜欢吃燃面5 小时前
C++刷题:日期模拟(1)
c++·学习·算法