【C++练习】普通方法+利用this 设置一个矩形类(Rectangle), 包含私有成员长(length)、 宽(width), 定义一下成员函数

题目

设置一个矩形类(Rectangle), 包含私有成员长(length)、 宽(width), 定义成员函数:

void set_ len(int l); //设置长度

设置宽度void set_ wid(int w);

获取长度: int get len();

获取宽度: int get _wid);

显示周长和面积: void show();

方法一:

代码

cpp 复制代码
#include <iostream>

using namespace std;
class Rectangle
{
    //不用写private,类内默认为私有
    int length;
    int width;
public:
    void set_len(int l);  //设置长度
    void set_wid(int w);  //设置宽度
    int get_len();  //获取宽度
    int get_wid();  //获取长度
    void show();    //显示周长和面积
};

int main()
{
    Rectangle r;    //实例化了一个Rectangle类的类对象r
    r.set_len(10);  //设置长度
    r.set_wid(3);   //设置宽度
    cout << "长:" << r.get_len() << endl;
    cout << "宽:" << r.get_wid() << endl;
    r.show();
    return 0;
}

void Rectangle::set_len(int l)
{
    length = l;
}
void Rectangle::set_wid(int w)
{
    width = w;
}
int Rectangle::get_len()
{
    return length;
}
int Rectangle::get_wid()
{
    return width;
}

void Rectangle::show()
{
    cout << "周长 = "<<(length+width)*2 << endl;
    cout << "面积 = "<<length*width << endl;
}

结果

方法二:利用this

代码

cpp 复制代码
#include <iostream>

using namespace std;
class Rectangle
{
    //不用写private,类内默认为私有
    int length;
    int width;
public:
    void set_len(int length);  //设置长度
    void set_wid(int width);  //设置宽度
    int get_len();  //获取宽度
    int get_wid();  //获取长度
    void show();    //显示周长和面积
};

int main()
{
    Rectangle r;
    r.set_len(10);  //设置长度
    r.set_wid(3);   //设置宽度
    cout << "长:" << r.get_len() << endl;
    cout << "宽:" << r.get_wid() << endl;
    r.show();
    return 0;
}

void Rectangle::set_len(int length)
{
    this->length = length;
}
void Rectangle::set_wid(int width)
{
    this->width = width;
}
int Rectangle::get_len()
{
    return length;
}
int Rectangle::get_wid()
{
    return width;
}

void Rectangle::show()
{
    cout << "周长 = "<<(length+width)*2 << endl;
    cout << "面积 = "<<length*width << endl;
}

结果

相关推荐
脉动数据行情19 分钟前
Go语言对接股票、黄金、外汇API实时数据教程
开发语言·后端·golang
yy_xzz24 分钟前
【OpenCV + VS】C++实现动态下雪特效
c++·人工智能·opencv
橘子真甜~1 小时前
C/C++ Linux网络编程5 - 网络IO模型与select解决客户端并发连接问题
linux·运维·服务器·c语言·开发语言·网络·c++
霖001 小时前
ZYNQ——ultra scale+ IP 核详解与配置
服务器·开发语言·网络·笔记·网络协议·tcp/ip
flypwn1 小时前
justCTF 2025JSpositive_player知识
开发语言·javascript·原型模式
oliveira-time1 小时前
原型模式中的深浅拷贝
java·开发语言·原型模式
2501_941111461 小时前
C++中的原型模式
开发语言·c++·算法
亿坊电商2 小时前
PHP框架的资源管理机制如何优雅适配后台任务?
开发语言·php
VBA63372 小时前
YZ系列工具之YZ09: VBA_Excel之读心术
开发语言
慢慢向上的蜗牛2 小时前
微软vcpkg包管理工具如何使用?
c++·microsoft·vcpkg·跨平台编译