函数调用运算符重载:
- 本质上就是重载双括号
()
- 重载后的函数称为仿函数
- 仿函数没有固定写法,非常灵活
代码:
class MyPrint {
public:
void operator()(string test) {
cout << test << endl;
}
void operator()(int i) {
cout << i << endl;
}
};
class MyAdd {
public:
int operator()(int a, int b) {
return a + b;
}
};
int main() {
string s = "hello";
MyPrint myPrint;
MyAdd myAdd;
myPrint(s);// 打印hello
myPrint(myAdd(1,1));// 打印2
//使用匿名对象来调用
myPrint(MyAdd()(1,3));// 打印4
return 0;
}
核心代码:
void operator()(string test) {
cout << test << endl;
}
void operator()(int i) {
cout << i << endl;
}
int operator()(int a, int b) {
return a + b;
}
需要注意的点:
- 调用仿函数的方式:
对象名(传入相应参数);
- 也可以用匿名对象来调用:
类名()(传入相应参数);
匿名对象的特点是执行完改行代码后立刻调用析构函数,释放对象空间,不再是执行完main方法后再调用对象的析构函数.