gpt4 book ai didi

c++ - 通过虚指针访问成员函数的指针

转载 作者:太空狗 更新时间:2023-10-29 21:39:33 25 4
gpt4 key购买 nike

我看到一些文章,其中解释了 vptr 和 vtable。我知道在存储了虚函数的类的情况下,对象中的第一个指针是 vtable 的 vptr,vtable 的数组条目是指向函数的指针,其顺序与它们在类中出现的顺序相同(我已经通过测试验证了程序)。但我试图了解编译器必须输入什么语法才能调用适当的函数。

示例:

class Base
{
virtual void func1()
{
cout << "Called me" << endl;
}
};
int main()
{
Base obj;
Base *ptr;
ptr=&obj;

// void* is not needed. func1 can be accessed directly with obj or ptr using vptr/vtable
void* ptrVoid=ptr;

// I can call the first virtual function in the following way:
void (*firstfunc)()=(void (*)(void))(*(int*)*(int*)ptrVoid);
firstfunc();
}

问题:

1. 但我真正想了解的是编译器如何用 vptr 替换对 ptr->func1() 的调用?如果我要模拟通话那么我应该怎么做?我应该重载 -> 运算符吗?但即使那样也无济于事,因为我不知道 func1 的真正名称是什么。即使他们说编译器通过 vptr 访问 vtable,它仍然如何知道 func1 的条目是第一个数组,func2 的条目是第二个元素大批?必须有一些函数名到数组元素的映射。

2.如何模拟。您能否提供编译器用于调用函数 func1 的实际语法(它如何替换 ptr->func1())?

最佳答案

不要将 vtable 视为数组。它只是一个数组,如果你去掉它的所有 C++ 知道的关于它的东西,除了它的成员的大小。相反,将其视为第二个 struct其成员都是指向函数的指针。

假设我有这样一个类:

struct Foo {
virtual void bar();
virtual int baz(int qux);
int quz;
}

int callSomeFun(Foo* foo) {
foo->bar();
return foo->baz(2);
}

将其分解为 1 个步骤:

class Foo;
// adding Foo* parameter to simulate the this pointer, which
// in the above would be a pointer to foo.
struct FooVtable {
void (*bar)(Foo* foo);
int (*baz)(Foo* foo, int qux);
}
struct Foo {
FooVtable* vptr;
int quz;
}

int callSomeFun(Foo* foo) {
foo->vptr->bar(foo);
return foo->vptr->baz(foo, 2);
}

我希望这就是您要找的。

关于c++ - 通过虚指针访问成员函数的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32676915/

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