c++ - 从父类(super class)调用子类中的虚函数

标签 c++ inheritance virtual

我知道这个问题一定被无数次问过,但我搜索了以前的问题,似乎什么也没有。

它是关于 C++ 中的继承和虚函数。我在从父类(super class)的子类中调用虚函数时遇到问题。

我举个例子。从三个相互继承的类开始。

class A {

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

};

class B : public A {

    virtual void bar() { }

};

class C : public B {

    virtual void bar() { // do something }

};

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

B* myObject = new C();
myObject->foo();

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

我如何告诉 A::foo(),它需要查看最低实现?

有道理吗?

//特伦斯科

编辑:

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

}

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

最佳答案

以下按预期打印“A::foo C::bar”。你得到不同的东西吗? B::bar从未被调用,因为 C是对象的实际运行时类型。在 C::bar , 你可以调用 B::bar显式地添加 B::bar();到它的 body 。

#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;
}

关于c++ - 从父类(super class)调用子类中的虚函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3540891/

相关文章:

c++多重继承和显式构造函数调用

c++ - 如何生成范围内的随机数 (-x,x)

c++ - 以非交互方式安装 boost 二进制文件

c++ - C++ 是否保证 cstdint sizeof 的顺序?

delphi - 如果没有显式调用,Delphi 是否调用继承于重写过程的方法

c++:使用 header 但并非没有时对vtable的 undefined reference

javascript - 创建孪生对象 a.k.a. 继承克隆

c# - 派生的 C# 接口(interface)属性是否可以覆盖同名的基本接口(interface)属性?

C++:在继承层次结构中的每个类中使用虚拟?

c++ - 虚拟类多重继承