考虑以下代码:
#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/