m0_61606978
2021-10-14 22:45
采纳率: 0%
浏览 10

关于c++返回函数指针问题

#include<iostream>
#include<vector>
#include<string>
using namespace std;
using pp = int(*)(int, int);
typedef int(*p)(int a, int b);
int pluss(int a, int b);
int multiplication(int a, int b);
int division(int a, int b);
int subtract(int a, int b);
int(*back_func(const string& str))(int, int);
int main(void)
{
    vector<p>a;
    a.push_back(back_func("pluss"));
    a.push_back(multiplication);
    a.push_back(division);
    a.push_back(subtract);
    for (size_t i = 0; i < a.size(); i++)
        cout << a[i](1, 1);
    cout << endl;
    vector<int>bbb;
    return 0;
}
int pluss(int a, int b)
{
    return a + b;
}
int multiplication(int a, int b)
{
    return a*b;
}
int division(int a, int b)
{
    return a/b;
}
int subtract(int a, int b)
{
    return a - b;
}
int(*back_func(const string& str))(int , int)
{
    decltype(pluss)* pp=0;
    if (str == "subtract")
        pp=subtract;
    else  if (str == "pluss")
        pp= pluss;
    if (str == "multiplication")
        pp= multiplication;
    else  if (str == "division")
        pp= division;
    return pp;
}

如果将back_func函数中的if条件后的pp= 改成return (直接返回函数指针)会发生运行时错误,出错行为主函数中的for循环。
请教下这是什么原因导致的?

  • 收藏

相关推荐 更多相似问题