我想從基礎知識中學習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