マップ データ構造の要素にキーでアクセスしようとしていますが、コンパイル エラーが発生します。マップのインスタンス化の構文を簡素化するために、typedef を使用してマップ データ構造を定義しました。ご覧のとおり、キーは型string
で、データはカスタムGameComponent
オブジェクトです。
typedef map<string, GameComponent*> ComponentMap;
typedef map<string, GameComponent*>::iterator ComponentMapIter;
typedef map<string, GameComponent*>::const_iterator ComponentMapCIter;
の派生クラスでGameComponent
、マップに格納されている一意の GameComponent オブジェクトごとに標準の Composite パターン メソッドとアクセサーを作成しています。ただし、配列添字演算子を使用してアクセサー内のオブジェクトにアクセスすると、コンパイラ エラーが発生します。
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