函数调用符()重载
为了优化类成员函数的调用,对函数调用符()进行重载
#include <iostream>
using namespace std;
class Fun
{
public:
int my_add(int x,int y)
{
return x+y;
}
//重载()
//第一个()是重载的符号 第二个()是标明要传参
int operator()(int x,int y)
{
return x+y;
}
};
void test01()
{
Fun fun;
cout<<fun.my_add(100,200)<<endl;
cout<<fun.operator ()(100,200)<<endl;
//优化 fun和()结合 就会自动寻找()运算符
cout<<fun(100,200)<<endl;
//此处 fun(100,200)不是一个真正的函数 仅仅是一个对象名和()结合 调用()重载运算符而已
//fun不是函数名 只是fun(100,200)类似一个函数调用 所以将fun(100,200)叫做仿函数
//此处的Fun是类名称
//Fun()匿名对象 Fun()(100,200) 就是匿名对象(100,200)
cout<<Fun()(100,200)<<endl;//了解
}
int main(int argc, char *argv[])
{
test01();
return 0;
}
不要重载&&、||
因为用户无法实现 && ||的短路特性。
&& 短路特性: A && B 如果A为假 B将不会执行
|| 短路特性: A || B 如果A为真 B将不会执行
#include <iostream>
using namespace std;
class Complex{
public:
Complex(int flag){
this->flag = flag;
}
Complex& operator+=(Complex& complex){
this->flag = this->flag + complex.flag;
return *this;
}
bool operator&&(Complex& complex){
return this->flag && complex.flag;
}
public:
int flag;
};
int main(){
Complex complex1(0); //flag 0
Complex complex2(1); //flag 1
//原来情况,应该从左往右运算,左边为假,则退出运算,结果为假
//这边却是,先运算(complex1+complex2),导致,complex1的flag变为complex1+complex2的值, complex1.a = 1
// 1 && 1
//complex1.operator&&(complex1.operator+=(complex2))
if (complex1 && (complex1 += complex2)){
//complex1.operator+=(complex2)
cout << "真!" << endl;
}
else{
cout << "假!" << endl;
}
return EXIT_SUCCESS;
}