2012-10-05 34 views
-1

嘿,我有一个包含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. 
} 

谁能帮我做这件事,而不必全球化的载体声明?

回答

2

您可以接收它作为函数参数:

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

我这样做是好的,但现在即时通报这两个错误。错误错误LNK2019:函数中引用的无法解析的外部符号“int __cdecl playGame(void)”(?playGame @@ YAHXZ)_main \t C:\ Users \ Conor \ Documents \ College \ DKIT - Year 2 - Repeat \ DKIT - 2年 - 第一学期 - 重复\游戏编程\ MaroonedCA1 \ MaroonedCA1 \ MaroonedCA1.obj \t MaroonedCA1 错误错误LNK1120:1周无法解析的外部\t C:\用户\康纳尔\文档\学院\ DKIT - 2年 - 重复\ DKIT - 第2年 - 第1学期 - 重复\游戏编程\ MaroonedCA1 \ Debug \ MaroonedCA1.exe MaroonedCA1 – Pendo826

+0

@ Prendo826:您还必须将调用更改为'playGame',以将库存作为参数传递。你没有在你的代码中显示这个调用,但我猜它不在'displayInventory'中。因此,最基本的问题是你在错误的地方定义了“库存”。将它移到可以传入*'playGame'和'displayInventory'的地方。 –

3

按引用传递的载体,这两个功能,在主申报呢?

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