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;
}

运行结果:

思维导图:

相关推荐
wuyoula8 分钟前
尹之盾企业版网络验证
服务器·开发语言·javascript·c++·人工智能·ui·c#
Via_Neo12 分钟前
区间dp算法
开发语言·javascript·算法
hi_ro_a15 分钟前
C++ 手撕 STL 底层:红黑树封装 mymap/myset
数据结构·c++·算法
小卓(friendhan2005)17 分钟前
基于Qt的音乐播放器项目
数据库·c++·qt
aq553560017 分钟前
Laravel 10.x重磅升级:PHP 8.1+新时代
开发语言·php·laravel
秋雨梧桐叶落莳23 分钟前
iOS——Masonry约束内容整理
开发语言·学习·macos·ios·objective-c·cocoa
tankeven23 分钟前
贪心算法(Greedy Algorithm)详解:从理论到C++实践
c++·算法
Hesionberger24 分钟前
LeetCode72.编辑距离(多维动态规划)
java·开发语言·c++·python·算法
郝学胜-神的一滴26 分钟前
从底层看透Linux高性能服务器:epoll自定义封装与超时清理实战
linux·服务器·c++·网络协议·tcp/ip·unix
Via_Neo32 分钟前
Bash Game
开发语言·bash