试图使用指针向量来调用函数来函数,但是它无法返回正确的值 - 这是我的编译器吗?

问题描述 投票:0回答:1
Edit: 因此,似乎每个人都在获得正确的输出,所以我的问题现在是这样:为什么我会得到错误的输出?为什么无论我使用变量还是字面意思,为什么第二个论点将变为零?不,我没有感到困惑,并放置了错误的变量,我进行了仔细检查。我正在使用Visual Studio2013。 我在第250页的Lippman,Lajoie和MOO的第五版C ++底漆进行练习,而我的第三次练习的代码为6.56,正在返回不正确的值。

I使指针的向量达到了INT类型(INT,INT)的功能,从而使该类型的四个函数(加法,减法,乘法和除法)添加到我的向量中。我试图用迭代器通过那些指针,将其命名为呼叫它们,但是对于Add2和减去,它返回了第一个参数的值,为MULT的0,即使Y也不等于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 << "\n\n"; 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 << "\n\n"; return x % y; } else { cout << "Cannot divide by zero.\n\n"; 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.

I也尝试了以下操作:(** fiter)(test1,test2)。我认为也许我没有足够的退出,需要将指针与迭代器以及迭代器以及迭代器以及相同的输出相同。

谢谢你

您的代码对我来说很好,我认为您可能会在迭代中混合变量(替换为test2 tes3)

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

会给你
c++ function pointers vector
1个回答
0
投票

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

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); }
    

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.