嘿,我有一个包含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.
}
任何人都可以在不必全局化矢量声明的情况下帮助我这样做吗?
答案 0 :(得分:3)
通过参考两个函数传递向量并在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");
}
答案 1 :(得分:2)
您可以将其作为函数参数接收:
int playGame(vector<string>& inventory)
{
inventory.push_back("sword");
}