C++之重载运算符(+)

实现:
一斤牛肉两块钱
一斤羊肉三块钱

通过运算符重载,实现牛肉+羊肉,实现牛肉 + 牛肉。

Coin.h

#pragma once
#include<iostream>
using namespace std;
class Coin
{
public:
	Coin(int money);
	string description();
private:
	int money = 0;
};

Coin.cpp

#include "coin.h"
#include<sstream>
Coin::Coin(int money) {
	this->money = money;
}
string Coin::description() {
	stringstream ret;
	ret << money ;
	return ret.str();
}

Cow.h

#pragma once
class Coin;
class Goat;
class Cow
{
public:
	Cow(int weight);
	friend Coin operator+(const Cow& cow1, const Cow& cow2);
	friend Coin operator+(const Cow& cow1, const Goat& goat);
private:
	int weigth = 0;
};


Cow.cpp

#include"Cow.h"
#include"coin.h"
#include"Goat.h"
Cow::Cow(int weigth) {
	this->weigth = weigth;
}

Goat.h

#pragma once
class Goat
{
public:
	Goat(int weigth);
	int getWeight()const;
private:
	int weigth = 0;
};

Goat.cpp

#include "Goat.h"
Goat::Goat(int weight) {
	this->weigth = weigth;
}
int Goat::getWeight()const
{
	return weigth;
}

主函数:

#include<iostream>
#include"coin.h"
#include"Cow.h"
#include"Goat.h"
Coin operator+(const Cow& cow1, const Cow& cow2) {
	int money = (cow1.weigth + cow2.weigth) * 2;
	return Coin(money);
}
Coin operator+(const Cow& cow1, const Goat& goat1) {
	int money = cow1.weigth*2 + goat1.getWeight()*3;
	return Coin(money);
}
int main() {
	Cow c1(100);
	Cow c2(200);
	Goat g1(100);
	Coin coin1 = c1 + c2;
	cout << coin1.description() << endl;
	Coin coin2 = c1 + g1;
	cout << coin2.description() << endl;
	system("pause");
	return 0;
}

在这里插入图片描述
运算符重载,同类的可以直接使变量,不同类型的不可以直接使用变量,需要调用方法.
请看+号重载,cow用到是成员
而goat用的就是方法

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值