0

我遇到了一个对我来说毫无意义但通过使用参数解决的问题。基本上,这有效:

void Inventory:: showInventory(char input)
{
    //char input[80];
    //cin >> input;
    //char inventoryRequest[] = "i";
    //int invent = strcmp (input,inventoryRequest);
    //compare the player input to inventoryRequest (i) to see if they want to look at inventory.
    if(input == 'i')
    {
    cout<< "\nYou have " << inventory.size() << " items.\n";
    cout << "----------------Inventory----------------\n";
    cout<< "\nYour items:\n";
    for (int i= 0; i< inventory.size(); ++i)
        cout<< inventory[i] << endl;
    }
    cout << "\n-----------------------------------------\n\n\n";


}

而不是这样:

void Inventory:: showInventory()
{
         char input;
    //char input[80];
    //cin >> input;
    //char inventoryRequest[] = "i";
    //int invent = strcmp (input,inventoryRequest);
    //compare the player input to inventoryRequest (i) to see if they want to look at inventory.
    if(input == 'i')
    {
    cout<< "\nYou have " << inventory.size() << " items.\n";
    cout << "----------------Inventory----------------\n";
    cout<< "\nYour items:\n";
    for (int i= 0; i< inventory.size(); ++i)
        cout<< inventory[i] << endl;
    }
    cout << "\n-----------------------------------------\n\n\n";


}

基本上我认为这是一样的。但显然不是当第一个有效而第二个无效时。任何人都可以对此有所了解。

4

3 回答 3

4

在第一个示例中,input是一个参数。它将由调用者使用他们选择传入的任何值进行初始化。

在第二个示例中,input是一个未初始化的变量。在它被分配之前读取它(就像你所做的那样)是未定义的行为,因为它当时包含垃圾。

于 2012-11-29T23:16:28.673 回答
1
void Inventory:: showInventory(char input)

^ 这允许参数传递。

这意味着您可以调用someInv.showInventory('s')该方法并将某些值传递给该方法,并且您传递的值将被分配给input该方法的本地范围内使用。


void Inventory:: showInventory()

^ 这不是;它只是input在方法的本地范围内声明,但您不能input从方法外部分配一些值。

此外,这实际上改变了方法的签名。因此,诸如此类的调用someInv.showInventory('s')将失败,除非您有一个同名的方法需要char

于 2012-11-29T23:15:49.190 回答
0

在第一种情况下,您可以char在调用时将 a 传递给函数:inventory.showInventory('i'). 这正是参数的用途。它们允许您将一些值传递给函数进行处理——就像数学中函数的参数一样。

In the second case, you have an uninitialized variable input and you attempt to compare it to 'i', resulting in undefined behaviour.

于 2012-11-29T23:16:47.443 回答