ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

使用友元函数重载运算符

2021-05-12 19:31:03  阅读:194  来源: 互联网

标签:友元 Sheep Pork const weight Cow int 运算符 重载


其他文件不变
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;
}

标签:友元,Sheep,Pork,const,weight,Cow,int,运算符,重载
来源: https://blog.csdn.net/qq_34606496/article/details/116718986

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有