从向量(c ++)中调用派生类函数 [英] Calling derived class functions from within a vector (c++)
问题描述
我有两个类:
class Object {
public:
Object();
virtual void update();
virtual void draw();
private:
protected:
int x, y, tick;
}
和
class Unit : public Object {
public:
Unit();
void update();
private:
protected:
}
然后在sepparate .cpp文件中定义构造函数和函数。
I then define the constructors and functions in sepparate .cpp files.
下面是对象的定义:
Object::Object() {
x = y = 0;
};
Object::update() {
tick ++;
};
Object::draw() {
// All my draw code is in here.
};
并且单位:
Unit::Unit() : Object() {
};
Unit::update() {
Object::update();
// Then there's a bunch of movement related code here.
};
一切正常,但我遇到一个问题,当尝试从向量内调用函数。
Everything works fine individually, but I run into a problem when trying to call functions from within a vector.
vector<Object> objects;
然后在我的void main()中执行:
I then do this in my void main():
for (int i = 0; i < objects.size(); i ++) {
objects[i].update();
objects[i].draw();
};
这样绘制一切正常,但它只调用update()的对象版本而不是定义的版本由派生类。我必须为我从派生的Object类派生的每个类型为它工作,或者有另一种方法来调用派生的函数?
This draws everything fine, but it only calls the Object verson of update() not the version as defined by the derived class. Do I have to make a vector for each type that I derive from the Object class for it to work, or is there another way to call the derived functions?
感谢提前 - Seymore
Thanks in advance - Seymore
推荐答案
是的,它调用 class Object
因为你有一个 class Object
对象的向量:
Yes, it calls methods of class Object
, because you have a vector of class Object
objects:
vector<Object> objects; // stores instances of class Object
可能的解决方案是使用指针向量:
The possible solution is to use a vector of pointers:
vector<Object*> objects;
objects.push_back( new Unit() );
然后通过指针调用:
for (int i = 0; i < objects.size(); i ++) {
objects[i]->update();
objects[i]->draw();
}
这篇关于从向量(c ++)中调用派生类函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!