C++入门学习十 运算符重载

什么是运算符重载?

把标准运算符(+,-,*,\)作用于类类型的对象。

关键字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。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值