


用重载了括号运算符的类创建的对象也叫函数对象或者仿函数
#include <iostream>
using namespace std;
void show(string str) {
cout << "普通函数:" << str << endl;
}
class Person {
public:
void operator()(string str) {
cout << "重载函数:" << str << endl;
}
};
void test() {
/* show("hello");
Person show;
show("hello");*/
/*上面输出
普通函数:hello
重载函数:hello*/
Person show;
::show("hello");//这一行想要调用全局函数,在方法面前加上::
show("hello");
/*上面输出
普通函数:hello
重载函数:hello*/
}
int main() {
test();
return 0;
}
本文介绍了如何通过重载C++类的括号运算符实现函数对象(仿函数),并展示了如何在`test()`函数中调用全局函数与类方法的例子。
327

被折叠的 条评论
为什么被折叠?



