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

结果

相关推荐
pps-key2 小时前
网络攻防入门:从“黑客梦”到合法实操(生存篇)
开发语言·web安全·php
汤姆宝库3 小时前
BPE分词器的完整实现:字节对合并与词表构建
开发语言·人工智能·c#
驭渊的小故事5 小时前
订单服务如何调用商品服务?一次 RestTemplate 跨服务调用入门
java·开发语言·php
南风84115 小时前
C++ 四种强制类型转换详解
c++
Sakura_j_h_5 小时前
MCP SDK 2.0 实战:用 MCPServer 搭本地笔记检索服务
开发语言·笔记·python·qt·ai工具·mcp·mcpserver
微笑星河q6 小时前
C++STL【vector】常用接口函数使用和迭代器失效问题
开发语言·c++
Eider19986 小时前
Python基础语法之并发相关3
开发语言·python
FRing036 小时前
vue2干货总结11(短信验证、登录功能、统一处理错误(响应拦截器)、将token信息存入vuex、vuex持久化处理)
开发语言·前端·javascript·vue.js·vue2
CS_Zero8 小时前
DeepSeek V4.1 Flash 1017 (Batch) 新手极速上手指南
开发语言·batch·deepseek
山楂树の8 小时前
Java 字符串高效处理:StringBuilder、StringBuffer、StringJoiner
java·开发语言