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

coo*_*roc 2 c++ polymorphism inheritance

有什么办法可以让我做以下工作,还是有办法解决?我肯定错过了什么.

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;
}
Run Code Online (Sandbox Code Playgroud)

Nim*_*Nim 7

使用dynamic_cast<>垂头丧气的指针派生类(不要忘记测试结果).

例如

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