【问题标题】:How to use function variables in the main?如何在 main 中使用函数变量?
【发布时间】:2012-10-05 12:56:10
【问题描述】:

嘿,我有一个包含 STL 容器向量的函数。

void displayInventory()
{
    vector<string> inventory;
    cout<< "You have " << inventory.size() << " items.\n";
    cout<< "\nYouritems:\n";
    for (int i= 0; i< inventory.size(); ++i)
    cout<< inventory[i] << endl;
}

我想在另一种方法玩游戏中使用实际向量。

int playGame()
{
    inventory.push_back("sword"); //This is an error. Expression must have class.
}

谁能帮我做到这一点,而不必全球化向量声明?

【问题讨论】:

    标签: c++ function vector


    【解决方案1】:

    通过引用两个函数来传递向量并在main中声明?

    int main()
    {
      vector<string> inventory;
      playGame(inventory);
      displayInventory(inventory);
    }
    
    void displayInventory(vector<string> &inventory)
    {
      inventory.push_back("string");
    }
    
    void playGame(vector<string> &inventory)
    {
      inventory.push_back("A second string");
    }
    

    【讨论】:

      【解决方案2】:

      您可以将其作为函数参数接收:

      int playGame(vector<string>& inventory)
      {
          inventory.push_back("sword");
      }
      

      【讨论】:

      • 我这样做很好,但现在我遇到了这两个错误。错误 7 错误 LNK2019:未解析的外部符号“int __cdecl playGame(void)”(?playGame@@YAHXZ) 在函数 _main C:\Users\Conor\Documents\College\DKIT - Year 2 - Repeat\DKIT - Year 2 - 中引用第 1 学期 - 重复\Games Programming\MaroonedCA1\MaroonedCA1\MaroonedCA1.obj MaroonedCA1 错误 8 错误 LNK1120:1 未解决的外部 C:\Users\Conor\Documents\College\DKIT - 第 2 年 - 重复\DKIT - 第 2 年 - 第 1 学期 -重复\游戏编程\MaroonedCA1\Debug\MaroonedCA1.exe 1 1 MaroonedCA1
      • @Prendo826:您还必须将调用更改为playGame,以将库存作为参数传递。您没有在代码中显示该调用,但我猜它不在displayInventory 中。因此,基本问题是您在错误的位置定义了inventory。将其移动到可以传递给 both playGamedisplayInventory 的位置。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-01-19
      • 2012-12-31
      • 2018-08-10
      • 2021-03-15
      • 2020-06-13
      • 1970-01-01
      相关资源
      最近更新 更多