7

这是我的代码。我不断收到此错误:

错误:“)”标记之前的预期主表达式

任何人有任何想法如何解决这个问题?

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

}
4

2 回答 2

7

showInventory(player);正在传递一个类型作为参数。这是非法的,你需要传递一个对象。

例如,类似:

player p;
showInventory(p);  

我猜你有这样的事情:

int main()
{
   player player;
   toDo();
}

这太可怕了。首先,不要将对象命名为与您的类型相同。其次,为了使对象在函数内可见,您需要将其作为参数传递:

int main()
{
   player p;
   toDo(p);
}

std::string toDo(player& p) 
{
    //....
    showInventory(p);
    //....
}
于 2012-10-13T20:46:40.063 回答
1
showInventory(player);     // I get the error here.

void showInventory(player& obj) {   // By Johnny :D

这意味着 player 是一种数据类型,而 showInventory 期望引用 player 类型的变量。

所以正确的代码将是

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

}
于 2012-10-13T20:54:29.467 回答