派生类对象在对象向量中重写基类的功能 [英] Derived class object override a function of base class in a vector of objects
问题描述
所以当存储在派生类的基类数组中时,我有一个调用派生类的重写函数的问题.
so I'm having an issue of calling the override function of a derived class when it's stored in an array of it's base class.
该基类称为Obstacle,而派生类为Cliff. Obstacle具有一个名为drawToBackground的虚拟函数,而从Obstacle继承来的Cliff也具有一个名为drawToBackground的函数,两者均无效.
The base class is called Obstacle, and the derived class is Cliff. Obstacle has a virtual function called drawToBackground, and Cliff, which inherits from Obstacle also has a function called drawToBackground, both of which are void.
然后我有了一个称为ObstsVec的障碍向量.在此向量中,我存储了一堆障碍物和一个悬崖.现在说悬崖是向量的第五个元素.当我调用obstsVec [5] .drawToBackground();时它从Obstacle类而不是悬崖类中调用drawToBackground函数.
I then have a vector of Obstacles, called obstsVec. In this vector, I store a bunch of Obstacles and a Cliff. Now say that the cliff is the fifth element of the vector. When I call obstsVec[5].drawToBackground(); it calls the drawToBackground function from the Obstacle class, not the cliff class.
这是c ++中的功能吗?或者我可能声明的内容有误?
Is this a feature in c++ or might I just have something declared wrong?
谢谢
推荐答案
您的类可能类似于:
#include <iostream>
#include <vector>
class Obstacles {
public:
Obstacles() {};
virtual void drawToBackground() {
std::cout << "Obstacle ";
}
};
class Cliff : public Obstacles {
public:
Cliff() : Obstacles() {};
virtual void drawToBackground() {
std::cout << "Cliff ";
}
};
int main(int argc, char* argv[]) {
std::vector<Obstacles*> vec;
vec.push_back(new Obstacles());
vec.push_back(new Cliff());
vec[1]->drawToBackground();
delete vec[1];
delete vec[0];
vec.clear();
}
您在上面提到了数组...请确保不要以多态使用数组,因为这将导致不确定的行为.
You mentioned arrays above...make sure never to use arrays polymorphically, as this will lead to undefined behaviour.
这篇关于派生类对象在对象向量中重写基类的功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!