c++ 多态性——使用基指针访问派生函数

标签 c++ inheritance polymorphism

有什么方法可以让我完成以下工作,或者有解决办法吗?我一定是遗漏了什么。

class base
{
public:
    int someInt;
    virtual void someFunction(){}
};

class derived : public base
{
public:
    void someFunction(){}
    void anotherFunction(){}
};

int main (int argc, char * const argv[]) {

    base* aBasePointer = new derived;

    aBasePointer->anotherFunction();

    delete aBasePointer

    return 0;
}

最佳答案

使用 dynamic_cast<> 向下转型指向派生类的指针(不要忘记测试结果)。

例如

if ((derived* p = dynamic_cast<derived*>(aBasePointer)))
{
  // p is of type derived.
  p->anotherFunction();
}

关于c++ 多态性——使用基指针访问派生函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9688652/

相关文章:

c++ - 重载对象成员的比较运算符

c++ - 关于 C++ vector::push_back() 异常。省略号catch有用吗?

Javascript 对象分配

php - 更改子类的 protected 变量的值

c++ - 以派生类作为参数的专用模板方法

c++ - 使用多态创建 'array of types'

c++ - QGraphicsRectItem 的几何形状

c++ - QObject:findChildren 和 QThread

python - 在python中覆盖类变量

Java继承之谜