纯虚拟对象是否有指向 vtbl 的指针?
纯虚拟对象是否有指向 vtbl 的指针? (这可能指向 NULL?)
谢谢,我对所有虚拟机制有点困惑。
Does a pure-virtual object have a pointer to the vtbl?
(that probably points to NULL?)
thanks, i'm a little bit confused with all the virtual mechanism.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
别担心。虚拟表是一个实现细节,甚至不能保证存在。你越担心如何完成,你对实际语言的了解就越少。
也就是说,是的。然后,具体类将设置该指针以指向正确的虚拟表。
Don't worry about it. Virtual tables are an implementation detail, and aren't even guaranteed to exist. The more you worry about how it might be done, the less you learn about the actual language.
That said, yes. A concrete class will then set that pointer to point to the correct virtual table.
从技术上讲,不存在“纯虚拟对象”这样的东西。我假设您指的是具有纯虚拟方法的对象?但您实际上无法创建这样的对象,因为它是抽象的并且编译器会抱怨。
话虽如此,在构造对象时,它在成为派生类的实例之前短暂地是抽象类的实例。在这种情况下,它将有一个虚拟表来设置它定义的函数。对于纯虚拟方法,它可能会有 NULL。如果你尝试调用该程序将会崩溃。
您可以通过在构造函数中调用虚方法来尝试这一点。如果您调用基类中的方法,您会发现它们调用基类版本。如果你调用纯虚方法,它就会崩溃。 (在某些情况下,编译器会弄清楚你在做什么并抱怨)。
结论是:
不要在构造函数中调用虚函数,这可能会造成混乱。事实上,在大多数情况下,最好是您的构造函数只设置其内部状态并且不执行任何过于复杂的操作。
There isn't technically such a thing as a 'pure-virtual object'. I assume you mean an object with pure-virtual methods? But you can't actually create such an object because it would be abstract and the compiler would complain.
Having said that, while the object is being constructed it is briefly an instance of the abstract class before becoming an instance of the derived class. It will in such a case have a virtual table set the functions it defines. It will probably have NULL for the pure virtual methods. If you try calling that the program will crash.
You can try this out by calling virtual methods in the constructor. You'll find they invoke the base class version if you call the methods in the base class. If you call a pure virtual method it'll crash. (In some cases the compiler will figure out what you are doing and complain instead).
The take home is:
Don't call virtual functions in your constructor, its just likely to be confusing. In fact, in most cases it is best if your constructor just sets its internal status up and does not do anything too complicated.