編程第七十天

c++ functional頭文件 auto用法

 1 #include <iostream>
 2 #include <functional>
 3 using namespace std;
 4 
 5 //仿函數,創建一個函數指針,引用一個結構體內部或者一個類內部的public公有函數
 6 
 7 struct MyStruct
 8 {
 9     void add1(int a)
10     {
11         std::cout << a << std::endl;
12     }
13 
14     void add2(int a, int b)
15     {
16         std::cout << a + b << std::endl;
17     }
18 
19     void add3(int a, int b, int c)
20     {
21         std::cout << a + b + c << std::endl;
22     }
23 };
24 
25 void main()
26 {
27     MyStruct struct1;//創建一個結構體變量
28 
29     //auto自動變量,地址,函數指針
30     //對於參數要使用佔位符 std::placeholders::_1
31     //auto 變量名 = bind(引用內部函數, 實體對象的地址, 佔位符);
32     auto func = bind(&MyStruct::add1, &struct1, std::placeholders::_1);
33 
34     auto func2 = bind(&MyStruct::add2, &struct1, std::placeholders::_1, std::placeholders::_2);
35 
36     auto func3 = bind(&MyStruct::add3, &struct1, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3);
37 
38     func(100);//100
39 
40     func2(10, 20);//30
41 
42     func3(10, 20, 30);//60
43 
44     //創建一個函數指針,指向結構體內部的函數。由於結構體的數據是獨有的,而函數是共享的,因此無法指向某個結構體變量的函數,只能指向結構體的函數
45     //函數通過調用,調用需要傳遞對象名
46     void(MyStruct::*p)(int) = &MyStruct::add1;//使用函數也可以解決,但是沒有bind好用    
47     
48     system("pause");
49 }

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章