使用友元函数重载运算符

其他文件不变
Cow.h

#pragma once

class Pork;
class Sheep;

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

	// 用友元函数实现运算符重载
	friend Pork operator+(const Cow &c1, const Cow &c2);
	friend Pork operator+(const Sheep &s1, const Cow &c2);

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

Cow.cpp

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

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

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"

//使用外部函数来调用类内的数据"weight",
//需要在类内声明友元函数,或者定义外部接口
Pork operator+(const Cow &c1, const Cow &c2) {
	int tmp = (c1.weight + c2.weight) * 2;
	return Pork(tmp);
}

Pork operator+(const Sheep &s1, const Cow &c1) {
	int tmp = ((s1.getWeight() * 3) + (c1.weight * 2));
	return Pork(tmp);
}


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

	//此时编译器会在代码里面找下面其中的一个方法
	// 1) c1.operator+(c1);
	// 2) operator+(c1, c2);
	p1 = c1 + c2;	
	p1.description();	//100斤牛 + 200斤牛 * 2  = 600斤猪

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

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值