我有一个函数,它接受一个Cp指针的向量,并将它们dynamic_cast成为派生指针的指针。当我尝试获取派生类的成员变量时,它崩溃了:
void DrawSystem::update(vector<Cp*> currentArgs)
{
cout << currentArgs[0]->type;
//Doesn't crash here
GraphicsCp* graphics = dynamic_cast<GraphicsCp*>(currentArgs[0]);
cout << graphics->type; //Crashes here
sf::Vector2f pos = dynamic_cast<PosCp*>(currentArgs[1])->pos;
cout << pos.x << " || " << pos.y << endl;
}
有谁知道这是为什么?
编辑: 以下是所有相关代码:
void GameObject::updateSystems() {
for(vector<System*>::const_iterator i = Systems.begin();
i != Systems.end();
++i) {
vector<Cp*> args;
for(vector<cptype>::const_iterator j = (*i)->args.begin();
j != (*i)->args.end();
++j) {
args.push_back(Cps[*j]);
}
(*i)->update(args);
}
}
class GameObject {
public:
GameObject();
virtual ~GameObject();
void addCp(const cptype&, Cp);
void addSystem(const systype&);
map <cptype, Cp*> Cps;
vector <System*> Systems;
void updateSystems();
virtual void update() {}
virtual void draw() {}
virtual bool isVisible() { return false; }
};
class GraphicsCp : public Cp {
public:
GraphicsCp(); //TEMP
GraphicsCp(sf::Texture*, sf::Vector2f);
virtual ~GraphicsCp();
sf::Sprite sprite;
sf::Vector2f frameDim;
sf::Vector2i currentTextureRectPos;
void update(Player& player, sf::RenderWindow&); //TEMP
private:
sf::RectangleShape rectangle; //TEMP
};
class Cp {
public:
Cp();
virtual ~Cp();
virtual void update() {} //TEMP
cptype type;
};
Player::Player() {
addCp("Pos", PosCp());
sf::Texture* texture = &Game::level.levelImageManager.playerSprite;
sf::Vector2f frameDim(54, 93);
addCp("Graphics", GraphicsCp(texture, frameDim));
addSystem("Draw");
}
void GameObject::addCp(const cptype& type, Cp cp) {
Game::level.levelCpManager.CpVecs[type].push_back(cp);
Cps[type] = &Game::level.levelCpManager.CpVecs[type].back();
}
void GameObject::addSystem(const systype& type) {
Systems.push_back(Game::level.levelSystemManager.systems[type].get());
}