为什么构造函数不返回值? [英] Why do constructors not return values?

查看:147
本文介绍了为什么构造函数不返回值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请告诉我为什么构造函数不返回任何值。我想要一个完美的技术原因向我的学生解释为什么构造函数没有任何返回类型。

Please tell me why the constructor does not return any value. I want a perfect technical reason to explain to my students why the constructor does not have any return type.

推荐答案

构造函数是运行时使用编译器生成的类型数据来确定在内存中存储对象实例需要多少空间,无论是在堆栈还是堆上。

What actually happens with the constructor is that the runtime uses type data generated by the compiler to determine how much space is needed to store an object instance in memory, be it on the stack or on the heap.

此空间包括所有成员变量和vtbl。分配此空间后,构造函数被称为实例化和初始化过程的内部部分,以初始化字段的内容。

This space includes all members variables and the vtbl. After this space is allocated, the constructor is called as an internal part of the instantiation and initialization process to initialize the contents of the fields.

然后,当构造函数退出时,运行时返回新创建的实例。因此,构造函数不返回值的原因是因为它不是由您的代码直接调用的,它由运行时中的内存分配和对象初始化代码调用。

Then, when the constructor exits, the runtime returns the newly-created instance. So the reason the constructor doesn't return a value is because it's not called directly by your code, it's called by the memory allocation and object initialization code in the runtime.

它的返回值(如果编译成机器代码时它实际上有一个值)对用户是不透明的,因此你不能指定它。

Its return value (if it actually has one when compiled down to machine code) is opaque to the user - therefore, you can't specify it.

这篇关于为什么构造函数不返回值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆