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;
}
相关推荐
万物得其道者成3 分钟前
React Zustand状态管理库的使用
开发语言·javascript·ecmascript
学步_技术9 分钟前
Python编码系列—Python抽象工厂模式:构建复杂对象家族的蓝图
开发语言·python·抽象工厂模式
BeyondESH31 分钟前
Linux线程同步—竞态条件和互斥锁(C语言)
linux·服务器·c++
wn53132 分钟前
【Go - 类型断言】
服务器·开发语言·后端·golang
豆浩宇40 分钟前
Halcon OCR检测 免训练版
c++·人工智能·opencv·算法·计算机视觉·ocr
Hello-Mr.Wang1 小时前
vue3中开发引导页的方法
开发语言·前端·javascript
救救孩子把1 小时前
Java基础之IO流
java·开发语言
WG_171 小时前
C++多态
开发语言·c++·面试
宇卿.1 小时前
Java键盘输入语句
java·开发语言
Amo Xiang1 小时前
2024 Python3.10 系统入门+进阶(十五):文件及目录操作
开发语言·python