gpt4 book ai didi

c++ - VTBL 是否包含指向非虚函数的指针?

转载 作者:行者123 更新时间:2023-11-27 22:44:14 26 4
gpt4 key购买 nike

<分区>

我很难理解为什么下面的代码打印 C::f2 而不是 B::f2。

From Charles Bailey answer:

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 的调用。编译器如何知道调用哪个方法?

我的假设:

  1. 编译器以某种方式记住我们在 C 类型的对象中。
  2. 编译器检查 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;
}

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com