重载

重载函数调用符号(operator())

把类对象像函数名一样使用。仿函数(functor),就是使一个类的使用看上去象一个函数。其实现就是类中实现一个operator(),这个类就有了类似函数的行为,就是一个仿函数类了。

class 类名 { 返值类型 operator()(参数类型) 函数体 }

#include <iostream>
using namespace std;
class Test {
public:	
	int operator()(int a) {
		return a*a;
	}
	double operator()(double b) {
		return b*b;
	}
};
void main() {	
	Test test;
	int x = test(5);
	double y = test(3.14);
	cout << "x=" << x << endl;
	cout << "y=" << y << endl;

执行代码得出以下结果:
在这里插入图片描述

不可以重载的&&和||操作符
#include <iostream>
using namespace std;
class Test {
public:	
	Test(int a) {
		this->a = a;
	}
	Test operator+(Test T) {
		cout << "执行+重载函数" << endl;
		Test temp(a = a + T.a);
		return temp;
	}
	bool operator&&(Test T) {
		cout << "执行&&重载函数" << endl;
		return a && T.a;
	}	
private:
	int a;
};
void main() {	
	int a = 1;
	int b = 2;
	if (a&&(a+b))//&& 与:两个条件中,两个同时为真,则结果为真,否则为假;
	{
		cout << "有一个是假,则不在执行下一个表达式的计算" << endl;
	}
	Test test1(1);
	Test test2(2);
	if (test1&&(test2+test1))
	{		
		test1.operator&&(test1.operator+(test2));
		cout << "&&的结合顺序是从左向右的,可它先执行了+" << endl;
	}
}

在这里插入图片描述

C++中如果重载&&或者||会无法实现短路规则:

(表达式1)&&(表达式2) 如果表达式1为假,则表达式2不会进行运算,即表达式2“被短路”
(表达式1)||(表达式2) 如果表达式1为真,则表达式2不会进行运算,即表达式2“被短路”
逻辑运算符运算规则:
&& 与:两个条件中,两个同时为真,则结果为真,否则为假;
|| 或:两个条件中,至少有一个为真,则结果为真,否则为假;

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值