C++的的运算符重载,成员函数,友元函数

main.cpp

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

int main()
{
	Cow c1(100);
	Cow c2(200);

	Goat g1(100);


	Pork p = c1 + c2;
	cout << p.description() << endl;

	p = c1 + g1;

	cout<<p.description();


	system("pause");
	return 0;
}

Cow.h

#pragma once
//需求:
// 规则:
// 一斤牛肉:2斤猪肉
// 一斤羊肉:3斤猪肉
class Pork;
class Goat;
class Cow
{
public:
	Cow(int weight);
	//Pork operator+(Cow&cow);
	//Pork operator +(Goat&goat);
	friend Pork operator+(const Cow &cow1,const Cow&cow2 );
	friend Pork operator +(const Cow &cow1,  Goat&goat);
private:
	int weight=0;
};

Cow.cpp

#include "Cow.h"
#include"Pork.h"
#include"Goat.h"

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

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

Pork Cow::operator+(Goat & goat)
{
	int tmp = this->weight * 2 + goat.getWeight() * 3;
	return Pork(tmp);
}*/

Pork operator+(const Cow & cow1, const Cow & cow2)
{
	int tmp = (cow1.weight + cow2.weight)*2;
	return Pork(tmp);
}

Pork operator+(const Cow & cow1,  Goat & goat)
{
	int tmp = cow1.weight * 2 + goat.getWeight() * 3;
	return Pork(tmp);
}

Pork.h

#pragma once
#include<string>
using namespace std;
class Pork
{
public:
	Pork(int weight);
	string description();

private:
	int weight = 0;
};

Pork.cpp

#include "Pork.h"
#include<sstream>
Pork::Pork(int weight)
{
	this->weight = weight;
}

string Pork::description()
{
	stringstream ret;
	ret << weight << "斤猪肉" << endl;
	return ret.str();
}

Goat.h

#pragma once
class Goat
{
public:
	Goat(int weight);
	int getWeight();

private:
	int weight = 0;
};

Goat.cpp

#include "Goat.h"

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

int Goat::getWeight()
{
	return weight;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值