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