自己開發了一個股票軟件,功能很強大,需要的點擊下面的鏈接獲取:
https://www.cnblogs.com/bclshuai/p/11380657.html
Bind函數詳解
目錄
1 簡介... 1
2 使用實例... 1
2.1 bind函數常規使用... 1
2.2 bind函數和thread線程函數... 3
3 原理解析... 4
3.1 一般函數綁定... 4
3.2 成員函數綁定... 5
3.3 Bind函數如何改變入參的順序... 5
1 簡介
bind函數的作用是通過綁定一個其他func函數生成一個依賴於func的新的函數對象,復用func函數的實現,但是可以改變這個func的參數數量和順序,可以綁定普通函數、全局函數,靜態函數,成員函數,而且其參數可以支持占位符(std::placeholders::_1,std::placeholders::_2)來改變參數的順序,並且可以設置func中默認的幾個參數來減少輸入參數的數量。
2 使用實例
2.1 bind函數常規使用
// BindTest.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <functional> #include <iostream> using namespace std; int add(int a, int b) { printf("normal function:%d+%d=",a,b ); return a + b; } class addClass { public: int add(int a, int b) { printf("member function:%d+%d=", a, b); return a + b; }; int extraAdd(int a, int b) { //printf("member extraAdd function:%d+%d=", a, b); auto classpointadd = std::bind(&addClass::add, this,a,b); return classpointadd(); }; }; int main() { //綁定靜態函數 auto fadd = std::bind(add, std::placeholders::_1, 4); cout<<fadd(2) << endl; //綁定成員函數,第一個參數需要是對象 addClass addobject; auto classadd = std::bind(&addClass::add, addobject, std::placeholders::_1, 3); cout <<classadd(2) << endl; //綁定成員函數,第一個參數也可以是指針 auto classpointadd = std::bind(&addClass::add, &addobject, std::placeholders::_1, 2); cout << classpointadd(2) << endl; //也可以在類的成員函數內部綁定成員函數,並且傳遞this指針 cout << addobject.extraAdd(1, 4) << endl; //占位符改變參數順序 auto changeOrder= std::bind(&addClass::add, addobject, std::placeholders::_2, std::placeholders::_1); cout << changeOrder(1,2) << endl;//輸入參數1,2,在add中參數變成2,1. getchar(); return 0; }
輸出結果
2.2 bind函數和thread線程函數
// BindTest.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <functional> #include <iostream> #include <thread> using namespace std; class threadBind { public: void StartThread() { m_ReconnectThread = std::move(thread(std::bind(&threadBind::Reconnect, this))); } void Reconnect() { while (true) { //do reconnect printf("thread func run\n"); break; } }; private: std::thread m_ReconnectThread; }; int main() { //線程函數綁定 threadBind thr; thr.StartThread(); getchar(); return 0; }
輸出結果
3 原理解析
3.1 一般函數綁定
Bind函數綁定函數時,會創建一個新的操作對象,對象內部有指向函數的指針和參數變量保存默認的參數。
3.2 成員函數綁定
綁定成員函數時,需要傳入對象的指針,不然bind找不到是調用哪個對象的成員函數。
3.3 Bind函數如何改變入參的順序
參數輸入函數時,默認是從左到右的順序,通過bind和占位符的順序,可以改變輸入參數的輸入順序。
//占位符改變參數順序
auto changeOrder= std::bind(&addClass::add, addobject, std::placeholders::_2, std::placeholders::_1);
參考文獻
https://www.cnblogs.com/xusd-null/p/3698969.html
https://www.cnblogs.com/jerry-fuyi/p/12633621.html
https://blog.csdn.net/u013654125/article/details/100140328