根据研究解释为什么构造函数不能为虚拟的:如果有错误,请纠正
我做了一些研究来找出为什么构造函数不能是虚拟的。我在这里巩固一下我的理解。
我将首先解释什么是虚函数,然后根据第一个解释解释为什么构造函数不能为虚函数。
什么是虚函数
?
虚函数是基类中的函数或方法,它 可以在派生类中通过函数重新定义或重写 相同的签名。换句话说,虚函数允许有一个 派生类中基类方法的自定义实现 班级。它需要使用
virtual
关键字进行声明。当时 虚函数调用,决定选择哪个版本 函数定义(在基类或派生类中)的位置是 运行时,取决于调用对象的类型(动态 绑定)。当一个函数被声明为虚函数时,它告诉编译器该函数 调用虚函数的对象的类型应该是 仅在运行时确定。然后根据对象的类型, 函数调用应该绑定到函数定义和 应调用适当的函数。
为什么构造函数
不能是虚拟的?
当一个函数被声明为虚函数时,它告诉编译器该函数 将调用该函数的对象的类型应该是 仅在运行时确定,然后调用适当的 基于对象类型的函数版本。
如果构造函数被声明为虚拟的,它会告诉 编译器应该调用构造函数的对象类型 在运行时确定。但对于构造一个对象来说,确切的 对象的类型应该在编译时而不是运行时知道。 这就是构造函数不能为虚拟的原因。
我希望 SO 成员纠正这两个答案中的错误(如果有)。我认为,如果您可以通过将其重写为您的答案来纠正答案,而不是仅仅指出错误,这将对我和其他人有所帮助。
I did some study to find out why a constructor cannot be virtual. I am consolidating my understanding here.
I will first explain what is a virtual function and then explain why a constructor cannot be virtual based on the first explanation.
What is a virtual function
?
A virtual function is a function or a method in the base class which
can be redefined or overriden in the derived class, by a function with
the same signature. In other words, virtual function allows to have a
customized implementation of the base class method in the derived
class. It needs to be declared with thevirtual
keyword. At the time
of virtual function invocation, the decision to choose which version
of the function definition(in the base class or derived class) is made at
run-time, depending on the type of the invoking object(dynamic
binding).When a function is declared virtual, it tells the compiler that the
type of the object which would invoke the virtual function should be
determined only during run-time. Then based on the type of the object,
the function call should be bound to the function definition and the
appropriate function should be invoked.
Why a constructor
cannot be virtual?
When a function is declared virtual, it tells the compiler that the
type of the object which would invoke the function should be
determined only during run-time, and then invoke the appropriate
version of the function based on the type of the object.If the constructor were to be declared virtual, it would tell the
compiler that type of object which would invoke the constructor should
be determined at run-time. But for constructing an object, the exact
type of object should be known at compile time rather than at run-time.
This is the reason why a constructor cannot be virtual.
I would like the SO members to correct the mistakes in both the answers, if any. I think it would help me and others, if you could correct the answers by re-writing it as your answers, rather than just pointing out the mistakes.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论