函数调用运算符重载

函数调用运算符重载
operator()(){}
函数调用运算符()也可以重载
由于重载后使用的方法非常想函数调用。因此称为仿函数
仿函数没有固定写法很灵活。

 

 1 #include<iostream>;
 2 #include<string>;
 3 using namespace std;
 4 class MyPrint
 5 {
 6 public:
 7 void operator() (string test)//函数调用符()重载;
 8 {
 9 cout << test << endl;
10 }
11 };
12 class MyAdd
13 {
14 public:
15 MyAdd() {}
16 MyAdd(int a,int b)
17 {
18 m_A = a;
19 m_B = b;
20 }
21 int operator()(int num1,int num2)
22 {
23 return num1 + num2;
24 }
25 int m_A;
26 int m_B;
27 
28 };
29 void test01()
30 {
31 MyPrint p1;
32 p1("hello");//相当于p1.operator()("hello");简写成p1("hello")
33 MyAdd p2(10, 10);//调用构造函数初始化
34 cout << p2.m_A << p2.m_B << endl;
35 int num=p2(30, 50);//调用仿函数相当于int num=p2.operator()(20,50);
36 cout << p2.m_A << p2.m_B << endl;
37 cout << num << endl;    
38 cout << MyAdd()(200, 200) << endl;     //MYAdd()(200,200)叫匿名函数对象当前行执行完匿名函数对象就释放掉了,
39                         //调用int MyAdd::operator()(int num1,int num2)
40                         //相当于 
41                         //MyAdd tem;
42                         //cout << tem.operator()(200, 200) << endl;
43 
44 return;
45 } 
46 int main()
47 {
48 test01();
49 system("pause");
50 return 0;
51 }

 

posted @ 2021-02-18 19:24  两天阿来  阅读(103)  评论(0)    收藏  举报