C++继承,如何解决这个问题

C++ inheritance, how solve this?

本文关键字:解决 问题 继承 何解决 C++      更新时间:2023-10-16

如何解决此问题?我想执行正确的方法。有什么办法解决这个问题吗?我想在一个循环中执行方法something。

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();
}

当我有很多基础班的孩子时,我不知道如何打字。

有几件事。

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

您需要在基类中将方法声明为virtual

解决方案是使something()成为virtual函数。

class Base {
public:
    virtual void something() {}
};
...
[in a function]
Base *p = new Child;
p->something(); //calls Child's something