简体   繁体   English

尝试从向量返回对象时收到“没有可行的重载operator []错误”

[英]Getting a "no viable overloaded operator[] error when trying to return an object from a vector

I am working on making a small text-based game, and am currently stuck trying to build a function that passes a string, which is the name of a weapon, and returns that weapon object from a vector. 我正在开发一个小型的基于文本的游戏,并且目前正试图构建一个传递字符串的函数,该字符串是武器的名称,并从矢量返回该武器对象。 Here are the relevant functions: 以下是相关功能:

//define weapons like this
Weapon* flimsyDagger = Weapon* (3, "Flimsy Dagger", 17, 4.0);

//store weapons in this vector, which stores all of the stats of each weapon
void Weapon::fillWeaponVector() {
    allWeapons.push_back(flimsyDagger);
}

//use this function to return the weapon by passing its name as it was defined (e.g. 'flimsyDagger') and return all stats
Weapon* Weapon::getWeaponStats(std::string weaponName) {
    return allWeapons[weaponName];
}

The error is occurring at the first square brace in the line return allWeapons[weaponName]; return allWeapons[weaponName];return allWeapons[weaponName];中的第一个方括号出现错误return allWeapons[weaponName]; . I have looked everywhere for a solution and haven't found anything that quite fits my situation. 我到处都在寻找解决方案,但找不到适合我情况的任何东西。 Any suggestions? 有什么建议么?

You claim that you're using a vector, but nothing in the code you've posted indicates that allWeapons is in fact a vector. 您声称您正在使用向量,但是您发布的代码中没有任何内容表明allWeapons实际上是向量。

If it is, you can't index a vector with a text string - indices for vectors must be integers. 如果是这样,则无法使用文本字符串为向量建立索引-向量的索引必须为整数。 As @Eljay suggests, using a std::map may be more appropriate. 正如@Eljay建议的那样,使用std::map可能更合适。 This allows you to look up the objects you store using a non-numeric key. 这使您可以使用非数字键查找存储的对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM