使用友元函数重载运算符

其他文件不变
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;
}
上一篇:大厂学院 - 设计模式与框架源码分析 「完结无密」


下一篇:Java之拷贝