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 分钟前
第五部分:第一节 - Node.js 简介与环境:让 JavaScript 走进厨房
开发语言·javascript·node.js
June`13 分钟前
专题二:二叉树的深度搜索(二叉树剪枝)
c++·算法·深度优先·剪枝
盛夏绽放18 分钟前
Python字符串常用方法详解
开发语言·python·c#
AI+程序员在路上1 小时前
XML介绍及常用c及c++库
xml·c语言·c++
好吃的肘子1 小时前
Elasticsearch架构原理
开发语言·算法·elasticsearch·架构·jenkins
guoguo05241 小时前
vs2019及以后版本cmd指定编译环境文件的路径
c++
软行2 小时前
LeetCode 每日一题 3341. 到达最后一个房间的最少时间 I + II
数据结构·c++·算法·leetcode·职场和发展
nlog3n2 小时前
Go语言交替打印问题及多种实现方法
开发语言·算法·golang
kaixin_learn_qt_ing2 小时前
Golang
开发语言·后端·golang
ddd...e_bug2 小时前
Shell和Bash介绍
开发语言·bash