为什么要使用运算符重载
C/C++的运算符,支持的数据类型,仅限于基本数据类型。
问题:一头牛+一头马 = ?(牛马神兽?)
一个圆 +一个圆 = ? (想要变成一个更大的圆)
一头牛 – 一只羊 = ? (想要变成4只羊,原始的以物易物:1头牛价值5只羊)
解决方案:
使用运算符重载
Cow.h //牛
#pragma once
class Pork;
class Sheep;
class Cow{ //牛
public:
Cow(int weight = 0);
//1斤牛肉 = 2斤猪肉 1斤羊肉 = 3斤猪肉
//使用运算符重载,来实现 一头牛 + 一头牛 = 多少斤猪肉?
//返回的是猪肉的重量
Pork operator+(const Cow &cow); //同类型进行运算,使用的很频繁
//使用运算符重载,来实现 一头牛 + 一只羊 = 多少斤猪肉?
Pork operator+(const Sheep &sheep); //不同类型进行运算,比较少见
private:
int weight; //牛的重量
};
Cow.cpp
#include "Cow.h"
#include "Pork.h"
#include "sheep.h"
Cow::Cow(int weight)
{
this->weight = weight;
}
Pork Cow::operator+(const Sheep &sheep)
{
//牛肉的重量*2 羊肉的重量*3
int tmp = (this->weight * 2) + (sheep.getWeight() * 3);
return Pork(tmp); //返回猪肉的构造参数
}
Pork Cow::operator+(const Cow &cow)
{
int tmp = (this->weight + cow.weight) * 2;
return Pork(tmp);
}
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"
int main(void) {
Cow c1(100); //100斤的牛
Cow c2(200); //200斤的牛
Sheep s1(100); //100斤的羊
Pork p1; //猪
//调用运算符重载+
p1 = c1 + c2; //此时调用的是: c1.operator+(c2);
p1.description(); //100斤牛 + 200斤牛 * 2 = 600斤猪
p1 = c1 + s1;
p1.description(); //(100斤牛 * 2) + (100斤羊 * 3) = 500斤猪
system("pause");
return 0;
}