【发布时间】:2021-10-27 09:48:40
【问题描述】:
首先,这个问题听起来很重复,但我通过谷歌探索了这个问题,但作为外行没有得到满意的答案
问题: 假设我们在父类和派生类中有 3 个虚函数,如下例所示
class Base1 {
public :
virtual void Print1() {
cout << "Print1 Base1" << endl;
}
virtual void Print2() {
cout << "Print1 Base1" << endl;
}
virtual void Print3() {
cout << "Print1 Base1" << endl;
}
};
class Derived : public Base1 {
public:
void Print1() {
cout << "Print1 Derived1" << endl;
}
void Print2() {
cout << "Print1 Derived2" << endl;
}
void Print3() {
cout << "Print1 Derived3" << endl;
}
};
int main()
{
Derived d;
Base1 *bptr = &d;
bptr->Print2(); // -> Here Derived::Print2() shall be called
return 0;
}
如上例所示,在main()中调用Derived::Print2()
这里,基类和派生类vTable应由3个虚函数的3个条目组成
[0] -> Address of Print1()
[1] -> Address of Print2()
[2] -> Address of Print3()
我想知道, 在运行时编译器如何在 Derived vTable 中搜索 Print2() ?
【问题讨论】:
-
在大多数实现中,内存中的每个对象都有一个指向其类型信息的指针,作为其图像的一部分,包括 vtable。虚拟方法调用是通过链接的 vtable 通过 this 指针间接实现的。
-
[1] -> Address of Print2() [2] -> Address of Print2()为什么会有两个Print2()指针?还是打错字了? -
运行时不使用名称;变成了“调用表中的第三个虚函数”,很琐碎。
-
@KamilCuk,是错字
-
仅供参考,在程序运行期间不会访问编译器。您可以在一台计算机上编译,然后在另一台没有编译器的计算机上运行程序。
标签: c++ function-pointers virtual-functions vtable