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;
}
相关推荐
鲸屿19529 分钟前
python之socket网络编程
开发语言·网络·python
没有梦想的咸鱼185-1037-16631 小时前
基于R语言机器学习方法在生态经济学领域中的实践技术应用
开发语言·机器学习·数据分析·r语言
向上的车轮1 小时前
基于go语言的云原生TodoList Demo 项目,验证云原生核心特性
开发语言·云原生·golang
The Chosen One9851 小时前
C++ : AVL树-详解
开发语言·c++
zzyzxb1 小时前
std::enable_shared_from_this
c++
SNAKEpc121382 小时前
QML和Qt Quick
c++·qt
PH_modest2 小时前
【Qt跬步积累】—— 初识Qt
开发语言·qt
hansang_IR2 小时前
【题解】洛谷 P4286 [SHOI2008] 安全的航线 [递归分治]
c++·数学·算法·dfs·题解·向量·点积
GanGuaGua2 小时前
Linux系统:线程的互斥和安全
linux·运维·服务器·c语言·c++·安全
怀旧,2 小时前
【C++】18. 红⿊树实现
开发语言·c++