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;
}