《C++ Primer》学习 之 函数指针相关用法

/*
  函数指针相关用法
*/

 

 1 #define _CRT_SECURE_NO_WARNINGS
 2 #define HOME
 3 //#define NDEBUG
 4 #include <iostream>
 5 #include <stdexcept>
 6 #include <cassert>
 7 #include <ctype.h>
 8 #include <locale>
 9 #include <iterator>
10 #include <cmath>
11 #include <string>
12 #include <vector>
13 #include <initializer_list>
14 #include <ctime>
15 using namespace std;
16 using ptrFun = int(*)(int, int);
17 
18 int myAdd(int x, int y)
19 {
20     return (x + y);
21 }
22 int mySub(int x, int y)
23 {
24     return (x - y);
25 }
26 
27 int myMul(int x, int y)
28 {
29     return (x * y);
30 }
31 
32 int myDiv(int x, int y)
33 {
34     if (0 == y)
35     {
36         std::cerr << "error : 除以0" << endl;
37         return -1;
38     }
39     else
40     {
41         return (x / y);
42     }
43 }
44 
45 void Compute(int x, int y, int (*p)(int, int))
46 {
47     cout << p(x, y) << endl;
48 }
49 
50 
51 int main(int argc, char **argv)
52 {
53 #ifdef HOME
54     //freopen("in", "r", stdin);
55     //freopen("out", "w", stdout);
56 #endif
57 
58     cout << "方法一:" << endl;
59     // 以下两种声明方式也是可以的
60     //vector<int(*)(int, int)> vecFunc;
61     //vector<ptrFun> vecFunc;
62     vector<decltype(myAdd)*> vecFunc;
63     vecFunc.push_back(myAdd);
64     vecFunc.push_back(mySub);
65     vecFunc.push_back(myMul);
66     vecFunc.push_back(myDiv);
67     for (int i = 0; i < vecFunc.size(); ++i)
68     {
69         cout << vecFunc[i](6, 3) << endl;
70         cout << (*vecFunc[i])(6, 3) << endl;
71         Compute(6, 3, vecFunc[i]);
72     }
73 
74     cout << endl << "方法二:" << endl;
75     decltype(myAdd) *p1 = myAdd, *p2 = mySub, *p3 = myMul, *p4 = myDiv;
76     vector<decltype(myAdd)*> vec1Func = { p1, p2, p3, p4 };
77     for (int i = 0; i < vec1Func.size(); ++i)
78     {
79         cout << vec1Func[i](6, 3) << endl;
80         cout << (*vec1Func[i])(6, 3) << endl;
81         Compute(6, 3, vec1Func[i]);
82     }
83 
84 #ifdef HOME
85     std::cerr << "Time elapsed: " << clock() / CLOCKS_PER_SEC << " ms" << endl
86         << "message: " << __FILE__ << endl
87         << "        : in function " << __func__
88         << " at line " << __LINE__ << endl
89         << "          Compiled on " << __DATE__
90         << " at " << __TIME__ << endl;
91 #endif
92     return 0;
93 }

 

posted @ 2016-03-23 16:33  JmingS  阅读(314)  评论(0编辑  收藏  举报