C++:返回函数的指针

问题

此程序已使用C++11新标准,使用GCC编译器请添加参数[ -std=c++0x ],其他编译器请查阅相关手册.

  1. 编写函数的声明,令其接受两个int形参并且返回类型也是int;然后声明一个vector对象,令其元素是指向该函数的指针.
  2. 编写4个函数,分别对两个int值执行加,减,乘,除运算;在上一题创建的vector对象中保存指向这些函数的指针.
  3. 调用上述vector对象中的每个元素并输出其结果.

C++.
image-2033

源代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
/*************************************************************************
    > File Name: test.6.56.cpp
    > Author: puruidong
    > Mail: 1@w1520.com
    > Created Time: 2014年03月17日 星期一 20时03分26秒
 ************************************************************************/

#include<vector>
#include<iostream>
#include<iterator>
using namespace std;
//将放入vector中函数指针进行运算,并输出值.
//test.6.54-test.6.56有关联.

int add(int a,int b){return a+b;}
int mins(int a,int b){return a-b;}
int mul(int a,int b){return a*b;}
int divs(int a,int b){return a/b;}

int (*re(int sa))(int,int)//返回函数指针:两个形参,函数名是re,包含两个形参,而函数名也包含了一个形参.它的返回类型是:int (*)(int,int).
{
    switch(sa)
    {
        case 0:
            return add;
            break;
        case 1:
            return mins;
            break;
        case 2:
            return mul;
            break;
        case 3:
            return divs;
            break;
    }
    return 0;
}

int main()
{
    int a=10,b=5;
    int (*pas)(int,int);//声明一个类型:包含两个形参的一个函数[函数名是pas],pas前面的*号表示其是一个指针,即函数指针
    vector<decltype(pas)> kess;//使用decltype关键字获取pas的准确类型
    for(int i=0;i<4;++i)//使用pas获取实际的函数指针.
    {
        pas=re(i);
        kess.push_back(pas);//添加到vector
    }
    vector<decltype(pas)>::iterator it=kess.begin();//依旧使用decltype获取准确类型.
    for(;it!=kess.end();++it)
    {
        cout << ((*it)(a,b)) << endl;//内联函数:解引用,计算值并输出值.
    }
    return 0;
}

参考了相关资料,具体请前往:[嗯,让我们彻底搞懂C/C++函数指针吧]