編譯錯誤我想通過鍵訪問地圖數據結構的元素,但得到一個編譯器錯誤。我已經使用typedefs定義了我的地圖數據結構,以簡化地圖實例化的語法。正如你所看到的,關鍵是string
類型和數據是定製GameComponent
對象:編譯時嘗試訪問std :: map元素與運算符[]
typedef map<string, GameComponent*> ComponentMap;
typedef map<string, GameComponent*>::iterator ComponentMapIter;
typedef map<string, GameComponent*>::const_iterator ComponentMapCIter;
在派生類中的GameComponent
,我創造與存取中存儲的每個獨特的GameComponent對象沿着標準的複合模式的方法我的地圖。但是,使用數組下標運算符可以訪問編譯器錯誤存取結果對象:
void Character::add(const string& key, GameComponent* comp)
{
m_components->insert(make_pair(key, comp));
}
void Character::remove(const string& key)
{
m_components->erase(key);
}
Armor* Character::getArmor() const
{
// ERROR:
return static_cast<Armor*>(m_components["Armor"]);
}
Weapon* Character::getWeapon() const
{
// ERROR:
return static_cast<Weapon*>(m_components["Weapon"]);
}
Attributes* Character::getAttributes() const
{
// ERROR:
return static_cast<Attributes*>(m_components["Attributes"]);
}
的編譯器錯誤的輸出顯示「無效型」的錯誤,其中有我抓我的頭:
/Users/Dylan/Desktop/RPG/character.cpp: In member function 'Armor* Character::getArmor() const':
/Users/Dylan/Desktop/RPG/character.cpp:66: error: invalid types 'ComponentMap* const[const char [6]]' for array subscript
/Users/Dylan/Desktop/RPG/character.cpp: In member function 'Weapon* Character::getWeapon() const':
/Users/Dylan/Desktop/RPG/character.cpp:71: error: invalid types 'ComponentMap* const[const char [7]]' for array subscript
/Users/Dylan/Desktop/RPG/character.cpp: In member function 'Attributes* Character::getAttributes() const':
/Users/Dylan/Desktop/RPG/character.cpp:76: error: invalid types 'ComponentMap* const[const char [11]]' for array subscript
是的,這是我最終使用的那個。謝謝。 – dtg