c++ std::vector of base class objects ---- 派生类的运行方法 [英] c++ std::vector of base class objects ---- running method of derived class
问题描述
我想问一下Java中的instanceof"之类的东西.我创建了一个简单的继承示例.我的想法是一个抽象类怪物和儿童骨架和僵尸,但抽象它不起作用,所以我们有 std::vectorBase 类.我将儿童对象推入向量.我想调用子类的方法,但调用的方法是基类空方法.有没有办法做到这一点?也许在 C++ 编程中我们应该避免这种代码思维并分别使用向量骨架和向量僵尸来实现?对不起我的英语不好.我希望你明白我的问题.
I would like to ask about something like "instanceof" in Java. I created a simple example of inheritence. My idea was made an abstarct class Monster and children Skeleton and Zombie, but with abstract it doesn't work, so We have std::vectorBase class. I pushed children objects into vector. I want to call method of children classes, but method which is called is base class empty method. Is existing any way to do it ? Maybe in c++ programming we should avoid this code thinking and do it using vector skeleton and vector zombie separately? Sorry for my english. I hope you understand my problem.
class Monster
{
public:
virtual void describe() {};
};
class Skeleton : public Monster
{
public:
Skeleton() {
}
~Skeleton(){}
void describe() override {
std::cout << "I am skeleton" << std::endl;
}
};
class Zombie : public Monster
{
public:
Zombie(){}
~Zombie(){}
void describe() override {
std::cout << "I am Zombie" << std::endl;
}
};
int main(void) {
std::vector<Monster> potwory;
potwory.push_back(Skeleton());
potwory.push_back(Zombie());
Skeleton sz;
Zombie z;
potwory.push_back(sz);
potwory.push_back(z);
for (auto i = 0; i < potwory.size(); i++) {
std::cout << typeid(potwory[i]).name() << std::endl; // each of them is Monster object
potwory[i].describe(); //here is calling method from base class , I want derived method.
}
std::cin.get();
return 0;
}`
推荐答案
如前所述,您遇到了切片问题,因为您只存储向量中所有对象的 Monster
部分.您可以使用 std::vector
或者,从 c++11 std::vector
开始,将指向 Monster
的指针/unique_ptr 存储在您的向量中.存储指向实际对象的指针可以减轻切片,因为对象不直接存储在向量中,而只是对堆上实际对象的引用,就像 Java 默认情况下所做的那样.
As mentioned, you ran into slicing as you only store the Monster
part of all objects in the vector.
You can either use std::vector<Monster*>
or, since c++11 std::vector<std::unique_ptr<Monster>>
, to store pointers/unique_ptr to Monster
in your vector. Storing a pointer to the actual object mitigates slicing as the object is not stored directly in the vector but only a reference to the actual object on the heap, like it is done it Java by default.
如果你真的需要值语义,你应该看看boost.polycollection 但恕我直言,这是一个相当高级的话题.
If you really need value-semantics, you should have a look at boost.polycollection but this is a rather advanced topic IMHO.
这篇关于c++ std::vector of base class objects ---- 派生类的运行方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!