我想从基础知识中学习C++,并且我正在玩弄函数指针。考虑到这一代码:太多的参数,函数指针中的参数太少
#include <iostream>
#include <string>
#include <vector>
bool print(std::string);
bool print(std::string a)
{
std::cout << a << std::endl;
return true;
}
bool call_user_function(bool(std::string), std::vector<std::string>);
bool call_user_function(bool(*p)(std::string), std::vector<std::string> args) {
if (args.size() == 0)
return (*p)(); (*)
else if (args.size() == 1)
return (*p)(args[0]);
else if (args.size() == 2)
return (*p)(args[0], args[1]); (**)
}
int main(int argc, char** argv)
{
std::vector<std::string> a;
a[0] = "test";
call_user_function(print, a);
// ok
return 0;
}
它给我:
main.cpp:28 (*): error: too few arguments to function
main.cpp:32 (**): error: too many arguments to function
我在做什么错?
'a [0] =“test”'是错误的,因为该向量不包含任何元素。如果它至少包含一个,那将起作用。 – GManNickG 2012-07-25 23:13:29
虽然不相关,但紧接在定义之前的函数声明什么也不做。 – 2012-07-25 23:13:57
@GManNickG,哦,我应该使用'push_back()'? – Shoe 2012-07-25 23:16:19