c++ - 调用姐妹类 C++ 的函数

标签 c++ inheritance multiple-inheritance overriding virtual-inheritance

考虑以下代码:

#include <iostream>

class A
{
public:
    virtual void f() = 0;
    virtual void g() = 0;
};

class B : virtual public A
{
public:
    virtual void f()
    {
        g();
    }
};

class C : virtual public A
{
public:
    virtual void g()
    {
        std::cout << "C::g" << std::endl;
    }
};

class D : public C, public B
{
};

int main()
{
    B* b = new D;
    b->f();
}

以下程序的输出是C::g

编译器如何调用B类的姊妹类的函数??

最佳答案

N3337 10.3/9

[ Note: The interpretation of the call of a virtual function depends on the type of the object for which it is called (the dynamic type), whereas the interpretation of a call of a non-virtual member function depends only on the type of the pointer or reference denoting that object (the static type) (5.2.2). — end note ]

动态类型是指针真正指向的类型,而不是声明为指向类型的类型。

因此:

D d;
d.g(); //this results in C::g as expected

等同于:

B* b = new D;
b->g();

并且因为在 B::f 中对 g() 的调用是(隐式)调用 this 动态类型D的指针,调用解析为D::f,也就是C::f .

如果您仔细观察,它与上面代码中显示的(完全)行为相同,只是 b 现在是隐式 this 代替。

这就是虚函数的全部意义。

关于c++ - 调用姐妹类 C++ 的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37653170/

相关文章:

c++ - 为什么 GCC 4.8.2 不传播 'unused but set' 优化?

C++:新手初始化列表问题

c++ - 通过 QTextStream 流式传输到 QTextEdit

c++ - 何时更喜欢基于模板策略的设计而不是基于非模板继承的设计

maven-2 - Maven : Using inherited property in dependency classifier causes build failure

python - 如何在多重继承中使用命名元组

c++ - 将 C++ 对象包装到 Node 插件中的 v8 对象

python - 基本继承(在python中)

Java抽象类实现了一个接口(interface),两者有相同的方法

c++ - C++ 中的自定义异常