什么是运算符重载?
把标准运算符(+,-,*,\)作用于类类型的对象。
关键字operator + 重载的运算符
在类的成员函数中定义
void operator>(const Cat& cat) {
if (age > cat.age) {
std::cout << name << "'s age is bigger than " << cat.name << "." << std::endl;
}
}
也可以在外部定义
inline void operator<(const Cat& cat1, const Cat& cat2) {
if (cat1.getAge() < cat2.getAge()) {
std::cout << cat1.getName() << "'s age is bigger than " << cat2.getName() << "." << std::endl;
}
}
与常量进行比较
inline void operator<(int otherAge, const Cat& cat2) {
if (otherAge < cat2.getAge()) {
std::cout << otherAge << " is smaller than " << cat2.getName() << "." << std::endl;
}
}
inline void operator<(const Cat& cat2, int otherAge) {
if (cat2.getAge() < otherAge) {
std::cout << cat2.getName() << " is smaller than " << otherAge << "." << std::endl;
}
}
如果重载了了 < 和 == ,可以使用utility头文件,在rel_ops命名空间中,自动生成<=,>=,!=的模板。但是需要注意,重载的< 和 == 返回类型一定要是bool。
#include <utility>
using namespace rel_ops;
// 重载运算符+,表示两个盒子对象的和,生成一个新的盒子
// main.cpp
#include <iostream>
#include "box.h"
int main() {
Box b1 = Box(1, 2, 3);
Box b2 = Box(4, 5, 6);
Box b3 = b1 + b2;
b3.showBox();
return 0;
}
//box.h
#include <iostream>
class Box
{
public:
Box(double lengthVal, double widthVal, double heightVal):
length{lengthVal},
width{widthVal},
height{heightVal}
{}
Box() = default;
void showBox() {
std::cout << "Box:" << length << " " << width << " " << height << std::endl;
}
Box operator+(const Box& aBox) {
return Box(std::max(length, aBox.length), std::max(width, aBox.width), height + aBox.height);
}
private:
double length;
double width;
double height;
};
函数对象:重载函数调用运算符()的类对象,也被称为functor。