实现:
一斤牛肉两块钱
一斤羊肉三块钱
通过运算符重载,实现牛肉+羊肉,实现牛肉 + 牛肉。
Coin.h
#pragma once
#include<iostream>
using namespace std;
class Coin
{
public:
Coin(int money);
string description();
private:
int money = 0;
};
Coin.cpp
#include "coin.h"
#include<sstream>
Coin::Coin(int money) {
this->money = money;
}
string Coin::description() {
stringstream ret;
ret << money ;
return ret.str();
}
Cow.h
#pragma once
class Coin;
class Goat;
class Cow
{
public:
Cow(int weight);
friend Coin operator+(const Cow& cow1, const Cow& cow2);
friend Coin operator+(const Cow& cow1, const Goat& goat);
private:
int weigth = 0;
};
Cow.cpp
#include"Cow.h"
#include"coin.h"
#include"Goat.h"
Cow::Cow(int weigth) {
this->weigth = weigth;
}
Goat.h
#pragma once
class Goat
{
public:
Goat(int weigth);
int getWeight()const;
private:
int weigth = 0;
};
Goat.cpp
#include "Goat.h"
Goat::Goat(int weight) {
this->weigth = weigth;
}
int Goat::getWeight()const
{
return weigth;
}
主函数:
#include<iostream>
#include"coin.h"
#include"Cow.h"
#include"Goat.h"
Coin operator+(const Cow& cow1, const Cow& cow2) {
int money = (cow1.weigth + cow2.weigth) * 2;
return Coin(money);
}
Coin operator+(const Cow& cow1, const Goat& goat1) {
int money = cow1.weigth*2 + goat1.getWeight()*3;
return Coin(money);
}
int main() {
Cow c1(100);
Cow c2(200);
Goat g1(100);
Coin coin1 = c1 + c2;
cout << coin1.description() << endl;
Coin coin2 = c1 + g1;
cout << coin2.description() << endl;
system("pause");
return 0;
}
运算符重载,同类的可以直接使变量,不同类型的不可以直接使用变量,需要调用方法.
请看+号重载,cow用到是成员
而goat用的就是方法