新聞中心
這里有您想知道的互聯(lián)網(wǎng)營(yíng)銷解決方案
C++零基礎(chǔ)教程之std:function函數(shù)包裝器
前言
C++中可調(diào)用對(duì)象的雖然都有一個(gè)比較統(tǒng)一的操作形式,但是定義方法五花八門,這樣就導(dǎo)致使用統(tǒng)一的方式保存可調(diào)用對(duì)象或者傳遞可調(diào)用對(duì)象時(shí),會(huì)十分繁瑣。C++提供了std::function和std::bind統(tǒng)一了可調(diào)用對(duì)象的各種操作。不同類型可能具有相同的調(diào)用形式。使用前記得加上functional頭文件。

成都創(chuàng)新互聯(lián)從2013年創(chuàng)立,是專業(yè)互聯(lián)網(wǎng)技術(shù)服務(wù)公司,擁有項(xiàng)目成都網(wǎng)站設(shè)計(jì)、成都網(wǎng)站制作網(wǎng)站策劃,項(xiàng)目實(shí)施與項(xiàng)目整合能力。我們以讓每一個(gè)夢(mèng)想脫穎而出為使命,1280元深澤做網(wǎng)站,已為上家服務(wù),為深澤各地企業(yè)和個(gè)人服務(wù),聯(lián)系電話:028-86922220
包裝普通函數(shù)
- #include
- #include
- #include
- using namespace std;
- int Max(int a, int b)
- {
- return a > b ? a : b;
- }
- void print()
- {
- cout << "無(wú)參無(wú)返回值" << endl;
- }
- int main()
- {
- function
funMax(Max); - cout << funMax(1, 2) << endl;
- function
funPrint(print); - print();
- printData(funMax, 1, 2);
- return 0;
- }
包裝類的靜態(tài)方法
- #include
- #include
- #include
- using namespace std;
- class Test
- {
- public:
- static void print(int a, int b)
- {
- cout << a + b << endl;
- }
- void operator()(string str)
- {
- cout << str << endl;
- }
- operator FuncPTR()
- {
- return print;
- }
- };
- int main()
- {
- //包裝類的靜態(tài)方法
- function
sFunc = Test::print; - sFunc(1, 2);
- return 0;
- }
包裝仿函數(shù)
- #include
- #include
- #include
- using namespace std;
- class Test
- {
- public:
- void operator()(string str)
- {
- cout << str << endl;
- }
- };
- int main()
- {
- //包裝仿函數(shù)
- Test test;
- function
funTest = test; - test("仿函數(shù)");
- return 0;
- }
包裝轉(zhuǎn)換成函數(shù)指針的對(duì)象 (operator的隱式轉(zhuǎn)換)
- #include
- #include
- #include
- using namespace std;
- using FuncPTR = void(*)(int, int);
- class Test
- {
- public:
- static void print(int a, int b)
- {
- cout << a + b << endl;
- }
- operator FuncPTR()
- {
- return print;
- }
- };
- int main()
- {
- //包裝轉(zhuǎn)換成函數(shù)指針的對(duì)象 (operator的隱式轉(zhuǎn)換)
- Test object;
- function
funOPE = object; - funOPE(2, 3);
- return 0;
- }
網(wǎng)站題目:C++零基礎(chǔ)教程之std:function函數(shù)包裝器
文章起源:http://m.fisionsoft.com.cn/article/dhgedgo.html


咨詢
建站咨詢
