使用成员函数实现运算符重载operator

为什么要使用运算符重载

C/C++的运算符,支持的数据类型,仅限于基本数据类型。

问题:一头牛+一头马 = ?(牛马神兽?)
一个圆 +一个圆 = ? (想要变成一个更大的圆)
一头牛 – 一只羊 = ? (想要变成4只羊,原始的以物易物:1头牛价值5只羊)

解决方案:
使用运算符重载

Cow.h //牛

#pragma once

class Pork;
class Sheep;

class Cow{	//牛
public:
	Cow(int weight = 0);

	//1斤牛肉 = 2斤猪肉		1斤羊肉 = 3斤猪肉
	
	//使用运算符重载,来实现  一头牛 + 一头牛 = 多少斤猪肉?
	//返回的是猪肉的重量
	Pork operator+(const Cow &cow);	//同类型进行运算,使用的很频繁
	
	//使用运算符重载,来实现  一头牛 + 一只羊 = 多少斤猪肉?
	Pork operator+(const Sheep &sheep);	//不同类型进行运算,比较少见
private:
	int weight;	//牛的重量
};

Cow.cpp

#include "Cow.h"
#include "Pork.h"
#include "sheep.h"

Cow::Cow(int weight)
{
	this->weight = weight;
}

Pork Cow::operator+(const Sheep &sheep)
{
				//牛肉的重量*2			羊肉的重量*3
	int tmp = (this->weight * 2) + (sheep.getWeight() * 3);
	return Pork(tmp);	//返回猪肉的构造参数
}

Pork Cow::operator+(const Cow &cow)
{
	int tmp = (this->weight + cow.weight) * 2;
	return Pork(tmp);
}

Sheep.h //羊

#pragma once

class Sheep{	//羊
public:
	Sheep(int weight = 0);
	int getWeight() const;

private:
	int weight;	//羊的重量
};

Sheep.cpp

#include "Sheep.h"

Sheep::Sheep(int weight)
{
	this->weight = weight;
}

int Sheep::getWeight() const
{
	return weight;
}

Pork.h //猪

#pragma once

class Pork{	//猪
public:
	Pork(int weight = 0);

	void description() const;
private:
	int weight;	//猪的重量
};

Pork.cpp

#include "Pork.h"
#include <iostream>

Pork::Pork(int weight)
{
	this->weight = weight;
}

void Pork::description() const
{
	std::cout << "猪的重量:" << weight << std::endl;
}

main.cpp

#include <iostream>
#include "Cow.h"
#include "Pork.h"
#include "sheep.h"

int main(void) {
	Cow c1(100);	//100斤的牛
	Cow c2(200);	//200斤的牛
	Sheep s1(100);	//100斤的羊
	Pork p1;		//猪

	//调用运算符重载+
	p1 = c1 + c2;		//此时调用的是: c1.operator+(c2);
	p1.description();	//100斤牛 + 200斤牛 * 2  = 600斤猪

	p1 = c1 + s1;		
	p1.description();	//(100斤牛 * 2) + (100斤羊 * 3) = 500斤猪

	system("pause");
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值