功能在另一个功能参数

时间:2016-12-04 02:45:54

标签: c++

好吧,基本上我已经浏览了所有q& a关于这个并且无法找到我的答案。

这是我的代码,它将对方形,立方体,数字的四分之一进行计算。但是,在尝试输出答案时出现错误。

#include <iostream>

using namespace std;
int square (int);  //n^2
int cube (int);  //n^3
int fourth (int);  //n^4
void powerN(int x[], const int sizex, void(*select)(int))
{
    cout<< x[sizex];
    cout<<" to the power of "<<sizex+2<<" is ";
    cout<<(*select)(x[sizex])<<endl;
}
int square (int a)
{
    return a*a;
}
int cube (int b)
{
    return b*b*b;
}
int fourth (int c)
{
    return c*c*c*c;
}
int main()
{
    int a[3]={3,4,5};
    for (int aSize=0;aSize<3;a++){
    powerN (a, aSize, square);
    powerN (a, aSize, cube);
    powerN (a, aSize, fourth);
    }
}

1 个答案:

答案 0 :(得分:0)

  1. 函数指针参数select的类型不正确。您将其返回类型声明为void,但不能cout。返回值应为int类型。

    void powerN(int x[], const int sizex, int(*select)(int))
    //                                    ~~~
    
  2. main()中的for循环,a++应为aSize++

  3. LIVE

相关问题