gpt4 book ai didi

c++ - 构造函数不能是虚拟的,为什么?不是骗子

转载 作者:太空狗 更新时间:2023-10-29 23:34:26 25 4
gpt4 key购买 nike

<分区>

Possible Duplicate:
Why do we not have a virtual constructor?

我知道之前有人问过这个问题,但我不明白其他答案中使用的复杂技术词汇。

我在社区上读到构造函数不能是虚拟的原因是

The ‘virtual’ mechanism works on a logically complete (completely constructed) object. We know that we use constructors to logically initialize our objects. In other words, the object is not completely constructed until the constructor has finished executing. Thus, we can’t have virtual constructors.

There is a misconception that by then virtual table is incomplete so we can’t have virtual constructors. Just before the constructor starts executing the virtual table is properly constructed and the ‘this’ pointer passed to the constructors. Moreover, virtual table mechanism is implementation depended, and finds no place in the C++ standard. And hence, to argue over this issue using the virtual table concept is illogical.

Now, as the constructor finishes executing any other function can be virtual. Destructor is no exception to this rule as it is a function. Virtual destructors are required in case we use a base class pointer to refer to a derived class object, use it, and then delete it. If we have virtual destructor, using ‘delete’, a chain of destructors is called starting from the derived to the base. But, had there been no ‘virtual’ in destructor only the base class destructor is called (and not the derived). This (may) generate inconsistencies in the program.

以上理由是否正确?答案不谈对象的静态类型和动态类型。

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