2024.3.14 C++

思维导图

封装类 用其成员函数实现(对该类的)数学运算符的重载(加法),并封装一个全局函数实现(对该类的)数学运算符的重载(减法)。

#include <iostream>
 
using namespace std;
//封装 货物Goods 类
class Goods
{
    //把全局函数设置为类的友元 方便访问私有成员进行运算
    friend const Goods operator-(const Goods &L,const Goods &R);
private:
    double price;//价格
    int num;//数量
public:
    Goods() {}//无参构造函数
    //有参构造函数
    Goods(double p,int m):price(p),num(m)
    {}
    //运算符重定义成员函数 实现+加法;
    const Goods operator+(const Goods &R)const
    {
        //定义临时类变量 存储计算后的结果并返回
        Goods temp;
        temp.price = price + R.price;
        temp.num = num + R.num;
        return temp;
    }
    void show()
    {
        cout << "价格:" << price << " 数量:" << num << endl;
    }
};
//封装运算符重定义一般函数 实现-减法;
const Goods operator-(const Goods &L,const Goods &R)
{
    //临时的类变量 存储计算结果并返回
    Goods temp;
    temp.price = L.price - R.price;
    temp.num = L.num - R.num;
    return temp;
}
int main()
{
    Goods g1(99.99,100);
    Goods g2(88.88,50);
    //等号右侧为(+加法)成员函数返回的临时值 Goods temp
    //Goods g3 = temp 调用拷贝构造函数完成初始化;
    Goods g3 = g1 + g2;
    //等号右侧为(-减法)全局函数返回的临时值 Goods temp
    //Goods g4 = temp 调用拷贝构造函数完成初始化;
    Goods g4 = g1 - g2;
    g3.show();
    g4.show();
    return 0;
}

  • 7
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值