<分区>
我很难理解为什么下面的代码打印 C::f2 而不是 B::f2。
When a non-virtual function is called the implementation must use the static type of the object on which the function is being called to determine the correct function to call. A function stored in a vtable accessed by a vptr will be dependent on the dynamic type of the object, not any static type of a reference or pointer through which it is being accessed.
我有点迷路了,在 A::f1 中有一个对 f2 的调用。编译器如何知道调用哪个方法?
我的假设:
- 编译器以某种方式记住我们在 C 类型的对象中。
- 编译器检查 C 是否包含非虚方法名 f2。 A。如果是,请运行它。 b.使用对象的指针访问他的 vtbl 并运行正确的 f2。
我说得对吗?
struct A
{
void f1()
{
f2();
}
virtual void f2()
{
cout<<"A::f2"<<endl;
}
};
struct B:public A
{
virtual void f2()
{
cout<<"B::f2"<<endl;
}
};
struct C:public B
{
void f2()
{
cout<<"C::f2"<<endl;
}
};
int main()
{
C c1;
c1.f1();
return 0;
}