编译错误我想通过键访问地图数据结构的元素,但得到一个编译器错误。我已经使用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