小编Bon*_*nic的帖子

重新解释为子类的父类可以在其函数中使用子类的函数吗?

我想在重新解释的类中从父函数调用子函数,如下所示。

例子

#include <iostream>

class A {
public:
    void func1() {
        // some code
        func2();
        // some code
    }
protected:
    virtual void func2() {
        printf("class A\n");
    }
};

class B : public A {
protected:
    virtual void func2() {
        printf("class B\n");
    }
};

int main() {
    A* ab = new A();
    ab->func1(); // this print "class A"

    B* bab = reinterpret_cast<B*>(ab);
    bab->func1(); // this also print "class A"
    // I want to print "class B" when I use bab->func1() 
} …
Run Code Online (Sandbox Code Playgroud)

c++ inheritance

1
推荐指数
1
解决办法
225
查看次数

标签 统计

c++ ×1

inheritance ×1