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

结果

相关推荐
博客18001 天前
酷宝的使用方法,超好用的免费界面库,C++、MFC可用
c++·mfc·界面库·库来帮·酷宝
郝学胜_神的一滴1 天前
CMake 026:属性体系精讲、四大作用域全解 & 实战代码落地
c++·cmake
众少成多积小致巨2 天前
JNI (Java Native Interface) 技术手册中文参考指南
android·java·c++
clint4566 天前
C++进阶(1)——前景提要
c++
夜悊6 天前
C++代码示例:进制数简单生成工具
c++
郝学胜_神的一滴6 天前
CMake 021: IF 条件判据详诠
c++·cmake
_wyt0017 天前
洛谷 B3930 [GESP202312 五级] 烹饪问题 题解
c++·gesp
LDR0067 天前
Type-C 快充全面升级!LDR6601 赋能个人护理便携电机,重塑剃须刀 / 理发器新体验
c语言·开发语言
雪碧聊技术7 天前
Tree.js是什么?一文讲透
开发语言·javascript·ecmascript
码云数智-园园7 天前
C++20 Modules 模块详解
java·开发语言·spring