试图使用指向函数的指针向量调用函数,但未能返回正确的值——这是我的编译器吗

Trying to call functions using a vector of pointers to functions, but it fails to return the correct value--is it my compiler?

本文关键字:函数 返回 编译器 我的 指针 调用 向量      更新时间:2023-10-16

编辑:所以看起来每个人都得到了正确的输出,所以我现在的问题是:为什么我得到了错误的输出?为什么第二个参数y变为零,不管我使用的是变量还是文字?不,我没有混淆,也没有放错变量,我仔细检查了一下。我正在使用Visual Studio 2013。

我正在做Lippman、Lajoie和Moo在第250页编写的C++入门第五版中的一个练习,第三个练习的代码6.56返回了不正确的值。

我制作了一个指向int(int,int(类型函数的指针向量,制作了四个该类型的函数(加法、减法、乘法和除法(,并将指向它们的指针添加到我的向量中。我试图用迭代器遍历这些指针,取消对它们的引用以调用它们,但对于add2和减法,它返回了第一个参数的值,0表示mult,else子句表示divide,尽管y不等于0。

代码如下:

int test(int x, int y);
int add2(int x, int y);
int subtract(int x, int y);
int mult(int x, int y);
int divide(int x, int y);
typedef decltype(test) *FuncP; //type declaration of a ptr to a function that takes two ints and returns int
int main(){
//6.7
vector<FuncP> ptrsToFuncs;
ptrsToFuncs.push_back(*add2);
ptrsToFuncs.push_back(*subtract);
ptrsToFuncs.push_back(*mult);
ptrsToFuncs.push_back(*divide);
vector<FuncP>::iterator fIter;
int test1 = 6, test2 = 8;
int test3 = 0;
cout << "Running four arithmetic functions with " << test1 << " and " << test2 << "nn";
for (fIter = ptrsToFuncs.begin(); fIter != ptrsToFuncs.end(); ++fIter)
{
    int result = (*fIter)(test1, test2);
    cout << result << endl;
}

    system("PAUSE");
}
int test(int x, int y)
{
    if (y != 0)
    {
        cout << "Modulo of one and two is: " << x % y << "nn";
    return x % y;
    }
    else
    {
        cout << "Cannot divide by zero.nn";
        return -1;
    }
}
int add2(int x, int y)
{
    cout << "Adding " << x << " and " << y << ": ";
    return (x + y);
}
int subtract(int x, int y)
{
    cout << "Subtracting " << x << " and " << y << ": ";
    return (x - y);
}
int mult(int x, int y)
{
    cout << "Multiplying " << x << " and " << y << ": ";
    return (x * y);
}
int divide(int x, int y)
{
    if (y != 0)
    {
        cout << "Dividing " << x << " and " << y << ": ";
        return (x / y);
    }
    else
    {
        cout << "Cannot divide by zero.n";
        return -1;
    }
}

例如,当test1=6和test2=8时,返回值将是:6,6,0,"不能除以零。"-1。

我也试过这个:(**ter((test1,test2(。我认为可能我没有足够的去引用,需要去引用指向函数和迭代器的指针,但它产生了相同的输出。

谢谢。

您的代码对我来说很好,我认为您可能在迭代中混淆了变量(用test3替换了test2到(

for (fIter = ptrsToFuncs.begin(); fIter != ptrsToFuncs.end(); ++fIter)
{
int result = (*fIter)(test1, test3);
cout << result << endl;
}

会给你

6,6,0,"不能被零除。"-1。

如果您需要查看代码在做什么,请尝试用文字替换变量,并在函数调用中添加一些cout。

 for (fIter = ptrsToFuncs.begin(); fIter != ptrsToFuncs.end(); ++fIter)
{
int result = (*fIter)(12, 24);
cout << result << endl;
}
int add2(int x, int y)
{
cout<<"add function called with first variable"<<x<<" and second variable"<<y<<endl;
return (x + y);
}