class BaseObj
{
public:
int position;
};
class EnemyObj: public BaseObj
{
public:
int quantity;
};
class PlayerObj: public BaseObj
{
public:
int lives;
};
int main()
{
BaseObj* myObjs[3];
BaseObj* b = new BaseObj();
b->position = 1;
myObjs[0] = b;
EnemyObj* e = new EnemyObj();
e->position = 2;
e->quantity = 5;
myObjs[1] = e;
PlayerObj* p = new PlayerObj();
p->position = 3;
p->lives = 2;
myObjs[2] = p;
myObjs[2]->lives = 2; // error is here
return 0;
}
我的問題是,我想有我所有的遊戲對象的數組,所以我可以把它們都在一起,但是當我嘗試訪問 myObjs [2] - >生活 我無法這樣做。這是我的錯誤:問題訪問派生類在陣列
error C2039: 'lives' : is not a member of 'BaseObj'
你不應該真的多態地使用數組。你最好使用std :: vector。一個相當好的解釋,爲什麼可以在這裏找到http://stackoverflow.com/questions/1043402/why-this-code-crashes – 2011-02-05 08:56:26