从超类调用子类中的虚函数

Tre*_*kow 5 c++ virtual inheritance

我知道这个问题肯定已被无数次覆盖,但我已经搜索过以前的问题,似乎没有任何东西可以流行.

它是关于C++的继承和虚函数.我在从超类中调用子类中的虚函数时遇到问题.

让我举个例子.从三个类开始,它们相互继承.

class A {

    void foo() { bar() }
    virtual void bar() { }

};

class B : public A {

    virtual void bar() { }

};

class C : public B {

    virtual void bar() { // do something }

};
Run Code Online (Sandbox Code Playgroud)

现在我想要一个声明为B*的变量,但实例化为C*.

B* myObject = new C();
myObject->foo();
Run Code Online (Sandbox Code Playgroud)

当我这样做,并在myObject上调用foo()时,A :: foo()调用bar().但是只调用B :: bar(),而不是C :: Bar() - 实际上是myObject,即使它被声明为B,它再次影响"//什么都不做"不会被执行.

我怎么告诉A :: foo(),它需要查看最低的实现?

说得通?

// Trenskow

编辑:

C :: Foo不是问题.Foo在A级被调用,因为它是它实现的唯一地方.当A:Foo调用Bar()时出现问题.然后B:Bar被调用而不是C :: Bar.

也许问题是,在我的实现中,我只得到一个指向A中对象的void*指针.

像这样:

void A:Foo(void *a) {

    A* tmpA = static_cast<A*> (a);
    tmpA->bar();

}
Run Code Online (Sandbox Code Playgroud)

现在编译器认为,tmpA是A.但不知怎的,它设法确定它是一个B*,并调用B :: Bar,实际上tmpA是一个C*,它应该调用C :: Bar.

Chr*_*ich 5

以下按预期打印"A :: foo C :: bar".你有不同的东西吗? B::bar永远不会被调用,因为它C是对象的实际运行时类型.在C::bar,您可以B::bar通过添加B::bar();到其正文明确调用.

#include <iostream>
using namespace std;

class A {
public:
    void foo() { cout << "A::foo "; bar(); }
    virtual void bar() { }
};

class B : public A {
public:
    virtual void bar() { cout << "B::bar" << endl; }
};

class C : public B {
public:
    virtual void bar() { cout << "C::bar" << endl; }
};

int main()
{
    B* c = new C();
    c->foo();
    return 0;
}
Run Code Online (Sandbox Code Playgroud)