C++作业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
{
private:
    int width;
    int height;
public:
    void init(int w, int h);
    void set_w(int w);
    void set_h(int h);
    void show();
};

void Rect::init(int w, int h)
{
    this->width = w;
    this->height = h;
}

void Rect::set_w(int w)
{
    this->width = w;
}

void Rect::set_h(int h)
{
    this->height = h;
}

void Rect::show()
{
    cout << "周长为:" << width+height << endl;
    cout << "面积为:" << width*height << endl;
}

int main()
{
    int height,width;
    Rect s1;
    s1.init(5,10);
    cout << "初始的周长和面积:" << endl;
    s1.show();
    cout << "请输入要更改的长和宽:";
    cin >> height >> width;
    s1.set_h(height);
    s1.set_w(width);
    s1.show();
    return 0;
}

运行结果:

思维导图:

相关推荐
似水明俊德3 分钟前
01-C#.Net-泛型-面试题
java·开发语言·面试·c#·.net
leonkay22 分钟前
Golang语言闭包完全指南
开发语言·数据结构·后端·算法·架构·golang
Allnadyy32 分钟前
【C++项目】从零实现高并发内存池(一):核心原理与设计思路
java·开发语言·jvm
雅欣鱼子酱38 分钟前
Type-C供电PD协议取电Sink芯片ECP5702,可二端头分开供电调整亮度,适用于LED灯带户外防水超亮灯条方案
c语言·开发语言
似水明俊德1 小时前
07-C#
开发语言·c#
浩子智控1 小时前
python程序打包的文件地址处理
开发语言·python·pyqt
casual~1 小时前
第?个质数(埃氏筛算法)
数据结构·c++·算法
Jackey_Song_Odd1 小时前
Part 1:Python语言核心 - 序列与容器
开发语言·windows·python
Elnaij2 小时前
从C++开始的编程生活(20)——AVL树
开发语言·c++
似水明俊德2 小时前
12-C#
开发语言·数据库·oracle·c#