函數調用運算符重載:
- 本質上就是重載雙括号
()
- 重載後的函數稱為仿函數
- 仿函數沒有固定寫法,非常靈活
代碼:
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方法後再調用對象的析構函數.