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;
}
会给你
如果您需要查看您的代码在做什么,请尝试用文字替换变量,并在函数调用中添加一些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);
}