1

How can I solve this? I want to execute proper method something. Is there any way to solve this? I want to execute method something in one loop.

class Base
{
public:
    void something() {}
};

class Child : public Base
{
public:
    void something() {}
};

class SecondChild : public Base
{
public:
    void something() {}
};

std::vector<Base*> vbase;

Child * tmp = new Child();

vbase.push_back((Base*) tmp);

SecondChild * tmp2 = new SecondChild();

vbase.push_back((Base*) tmp);

for (std::vector<Base*>::iterator it = vbase.begin(); it != vbase.end(); it++)
{
    //here's problem, I want to execute proper method "something", but only I can do is execute Base::something;
    (*it)->something();
}

I don't know how to cast type, when I got many children of base class.

4

3 回答 3

10

有几件事。

一,您不需要将东西投射到(Base*). 隐式转换已经为您做到了。其次,如果您定义函数,virtual它将为您调用正确的函数。

于 2013-07-16T17:01:03.260 回答
4

您需要像virtual在基类中一样声明该方法。

于 2013-07-16T17:01:04.203 回答
3

解决方案是制作something()一个virtual函数。

class Base {
public:
    virtual void something() {}
};
...
[in a function]
Base *p = new Child;
p->something(); //calls Child's something
于 2013-07-16T17:01:27.140 回答