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;
}
相关推荐
2501_9449347335 分钟前
高职大数据技术专业,CDA和Python认证优先考哪个?
大数据·开发语言·python
黎雁·泠崖1 小时前
【魔法森林冒险】5/14 Allen类(三):任务进度与状态管理
java·开发语言
2301_763472462 小时前
C++20概念(Concepts)入门指南
开发语言·c++·算法
阿猿收手吧!2 小时前
【C++】std::promise原理与实战解析
c++
TechWJ2 小时前
PyPTO编程范式深度解读:让NPU开发像写Python一样简单
开发语言·python·cann·pypto
lly2024063 小时前
C++ 文件和流
开发语言
m0_706653233 小时前
分布式系统安全通信
开发语言·c++·算法
Zach_yuan3 小时前
深入浅出 JSONCpp
linux·服务器·网络·c++
寻寻觅觅☆3 小时前
东华OJ-基础题-104-A == B ?(C++)
开发语言·c++
lightqjx4 小时前
【C++】unordered系列的封装
开发语言·c++·stl·unordered系列