C++ 如何修复“')' 标记之前的预期主表达式”错误?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12876822/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I fix a "Expected Primary-expression before ')' token" error?
提问by Tux
Here is my code. I keep getting this error:
这是我的代码。我不断收到此错误:
error: expected primary-expression before ')' token
错误:')' 标记之前的预期主表达式
Anyone have any ideas how to fix this?
任何人有任何想法如何解决这个问题?
void showInventory(player& obj) { // By Johnny :D
for(int i = 0; i < 20; i++) {
std::cout << "\nINVENTORY:\n" + obj.getItem(i);
i++;
std::cout << "\t\t\t" + obj.getItem(i) + "\n";
i++;
}
}
std::string toDo() //BY KEATON
{
std::string commands[5] = // This is the valid list of commands.
{"help", "inv"};
std::string ans;
std::cout << "\nWhat do you wish to do?\n>> ";
std::cin >> ans;
if(ans == commands[0]) {
helpMenu();
return NULL;
}
else if(ans == commands[1]) {
showInventory(player); // I get the error here.
return NULL;
}
}
采纳答案by Luchian Grigore
showInventory(player);
is passing a type as parameter. That's illegal, you need to pass an object.
showInventory(player);
正在传递一个类型作为参数。这是非法的,您需要传递一个对象。
For example, something like:
例如,类似于:
player p;
showInventory(p);
I'm guessing you have something like this:
我猜你有这样的事情:
int main()
{
player player;
toDo();
}
which is awful. First, don't name the object the same as your type. Second, in order for the object to be visible inside the function, you'll need to pass it as parameter:
这太糟糕了。首先,不要将对象命名为与您的类型相同的名称。其次,为了使对象在函数内可见,您需要将其作为参数传递:
int main()
{
player p;
toDo(p);
}
and
和
std::string toDo(player& p)
{
//....
showInventory(p);
//....
}
回答by Adrian Herea
showInventory(player); // I get the error here.
void showInventory(player& obj) { // By Johnny :D
this means that player is an datatype and showInventory expect an referance to an variable of type player.
这意味着 player 是一种数据类型,而 showInventory 期望引用一个类型为 player 的变量。
so the correct code will be
所以正确的代码将是
void showInventory(player& obj) { // By Johnny :D
for(int i = 0; i < 20; i++) {
std::cout << "\nINVENTORY:\n" + obj.getItem(i);
i++;
std::cout << "\t\t\t" + obj.getItem(i) + "\n";
i++;
}
}
players myPlayers[10];
std::string toDo() //BY KEATON
{
std::string commands[5] = // This is the valid list of commands.
{"help", "inv"};
std::string ans;
std::cout << "\nWhat do you wish to do?\n>> ";
std::cin >> ans;
if(ans == commands[0]) {
helpMenu();
return NULL;
}
else if(ans == commands[1]) {
showInventory(myPlayers[0]); // or any other index,also is not necessary to have an array
return NULL;
}
}