標籤:primer space tput type lin back use for tor
簡單的樣本:
#include <iostream>using namespace std;int sum(int x, int y){ return x + y;}int main(){ cout << sum(1, 2) << endl; int (*pf)(int, int); // 未初始化 pf = sum; cout << pf(3, 4) << endl; /* output: 3 7 */ return 0;}
遇到重載的情況,編譯器通過指標類型精確匹配函數。
#include <iostream>using namespace std;int sum(int x, int y){ return x + y;}int sum(int x, double y){ cout << "sum2" << endl; return x + y;}int main(){ cout << sum(1, 2) << endl; int (*pf)(int, int); // 未初始化 pf = sum; cout << pf(3, 4) << endl; /* output: 3 7 */ return 0;}
將函數作為參數:
#include <iostream>using namespace std;int sum(int x, int y){ return x + y;}typedef decltype(sum) func;int useInt2(int x, int y, func f){ return f(x, y);}int main(){ cout << useInt2(3, 4, sum) << endl; /* output = 7 */ return 0;}
傳回型別不會自動地轉換成指標,我們必須顯示地將傳回型別指定為指標,但是我想,除非是函數內部還可以建構函式(例如Python那樣),否則返回函數也沒什麼用。
練習
6.54
#include <iostream>#include <vector>using namespace std;int sum(int x, int y){ return x + y;}int main(){ using pf = int(*)(int, int); vector<pf> pfvec; return 0;}
6.55 & 6.56
#include <iostream>#include <vector>using namespace std;int add(int x, int y){ return x + y;}int subtract(int x, int y){ return x - y;}int multiply(int x, int y){ return x * y;}int divide(int x, int y){ return x / y;}int main(){ using pf = int(*)(int, int); vector<pf> pfvec; pfvec.push_back(add); pfvec.push_back(subtract); pfvec.push_back(multiply); pfvec.push_back(divide); for (pf f : pfvec) { cout << f(12 , 4) << endl; } return 0;}
輸出結果:
168483
【c++ primer, 5e】函數指標