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

结果

相关推荐
sqmw1 小时前
MFCMouseEffect:把桌面输入反馈这件事,做成一个真正可扩展的引擎
c++·插件·引擎·鼠标特效·键鼠指示·鼠标伴宠
globaldomain1 小时前
什么是用于长距离高速传输的TCP窗口扩展?
开发语言·网络·php
沈阳信息学奥赛培训2 小时前
#undef 指令 (C/C++)
c语言·开发语言·c++
2401_873204652 小时前
分布式系统安全通信
开发语言·c++·算法
Dxy12393102163 小时前
JS发送请求的方法详解
开发语言·javascript·ecmascript
sw1213893 小时前
C++中的代理模式实战
开发语言·c++·算法
難釋懷3 小时前
Lua语法入门-条件控制、函数
开发语言·junit·lua
桌面运维家3 小时前
Win10打印机共享故障排查:权限与网络配置详解
开发语言·网络·php
Sunshine for you4 小时前
实时操作系统中的C++
开发语言·c++·算法
史蒂芬_丁4 小时前
C++深度拷贝例子
java·开发语言·c++