C++ c++;通过引用将映射传递到函数中
如何通过C++ c++;通过引用将映射传递到函数中,c++,map,pass-by-reference,C++,Map,Pass By Reference,如何通过reference将map传递到函数中?Visual Studio 2010给了我一个未解决的外部问题错误。目前,我有以下简化代码: void function1(){ map<int, int> * my_map = new map<int, int>(); function2(*my_map); } void function2(map<int, int> &temp_map){ //do stuff with
reference
将map
传递到函数中?Visual Studio 2010给了我一个未解决的外部问题
错误。目前,我有以下简化代码:
void function1(){
map<int, int> * my_map = new map<int, int>();
function2(*my_map);
}
void function2(map<int, int> &temp_map){
//do stuff with the map
}
我得到的错误是:
Error 1 error LNK2019: unresolved external symbol "public: int __thiscall ComputerPlayer::analyzePlay(int,class Board,class std::map<int,int,struct std::less<int>,class std::allocator<struct std::pair<int const ,int> > > &)" (?analyzePlay@ComputerPlayer@@QAEHHVBoard@@AAV?$map@HHU?$less@H@std@@V?$allocator@U?$pair@$$CBHH@std@@@2@@std@@@Z) referenced in function "public: int __thiscallComputerPlayer::getBestMoves(void)" (?getBestMoves@ComputerPlayer@@QAEHXZ) C:\Users\Josh\Dropbox\Congkak_2\Congkak_2\ComputerPlayer.obj
Error 2 error LNK1120: 1 unresolved externals C:\Users\Josh\Dropbox\Congkak_2\Debug\Congkak_2.exe
错误1错误LNK2019:未解析的外部符号“public:int\uu thiscall ComputerPlayer::analyzePlay(int,类板,类std::map&)”(?analyzePlay@ComputerPlayer@@Qaehvboard@@AAV$map@HHU?$less@H@性病病毒$allocator@U?$pair@$$CBHH@std@@@函数“public:int\uu thiscallComputerPlayer::getBestMoves(void)”中引用了2@@std@@@Z)(?getBestMoves@ComputerPlayer@@QAEHXZ)C:\Users\Josh\Dropbox\Congkak_2\Congkak_2\ComputerPlayer.obj
错误2错误LNK1120:1未解析的外部C:\Users\Josh\Dropbox\Congkak_2\Debug\Congkak_2.exe
两件事:
- 在顶部添加
,并使用#包括
而不仅仅是std::map
map
- 在
上方定义function1
或至少在function2
上方声明function1
function2
#include<map>
void function2(std::map<int, int> &temp_map); //forward declaration
void function1(){
std::map<int, int> my_map; //automatic variable
//no need to make it pointer!
function2(my_map);
}
void function2(std::map<int, int> &temp_map){
//do stuff with the map
}
#包括
void function2(std::map和temp_map);//转发声明
无效函数1(){
std::map my_map;//自动变量
//不需要让它成为指针!
功能2(我的地图);
}
无效函数2(标准::映射和临时映射){
//用地图做些什么
}
还要注意的是,尽可能避免使用“新建”。默认情况下使用自动变量,除非您有非常充分的理由不使用它
自动变量速度快,代码看起来整洁干净。有了它们,编写异常安全代码就更容易了
编辑:
现在当你发布错误时,你也意识到
我忘了将函数所属的类添加到它的开头
,正如你在评论中所说
很好,你自己解决了。但是,当你问问题时,请始终在第一篇帖子中发布错误。记住这一点。未解决的外部错误意味着链接错误。我认为这与通过引用将映射传递到函数无关-这更可能是语法错误。此外,代码当我运行它时,它会自动运行。您的项目设置可能设置不正确。好的,我很确定我已经更改了需要更改的内容,但仍然会收到未解决的外部错误。我将在一分钟内用我在程序中实际使用的代码编辑我的原始帖子。@d2jxp:为什么不发布错误以及其他代码?我们的情况如何我想知道到底是什么错误吗?请记一下..我再次查看了我的代码,由于您的修复,它现在可以工作了。我忘了将函数所属的类添加到它的开头。如:Player::function2(std::map&temp_map){}…我还是添加了错误的代码。还没有做任何事情,但我想你明白了吗?@d2jxpL这很好。顺便说一句,当你问问题时,一定要在第一篇帖子中发布错误。记住这一点。
#include<map>
void function2(std::map<int, int> &temp_map); //forward declaration
void function1(){
std::map<int, int> my_map; //automatic variable
//no need to make it pointer!
function2(my_map);
}
void function2(std::map<int, int> &temp_map){
//do stuff with the map
}