天天看點

C++之重載運算符(+)

實作:

一斤牛肉兩塊錢

一斤羊肉三塊錢

通過運算符重載,實作牛肉+羊肉,實作牛肉 + 牛肉。

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;
}
           
C++之重載運算符(+)

運算符重載,同類的可以直接使變量,不同類型的不可以直接使用變量,需要調用方法.

請看+号重載,cow用到是成員

而goat用的就是方法

繼續閱讀