关于构造函数没有返回值的问题

来源:互联网 发布:守望先锋生涯数据查询 编辑:程序博客网 时间:2024/04/28 21:37

为什么构造函数不能有返回值?

摘自 <<Think in java>>

   “构造函数是一种很特殊的函数,因为他没有返回值。这和‘返回值为void’有极大的差别。返回void时,一般函数并不返回任何东西,但是一般的函数能够选择是否要返回些什么东西。构造函数则绝对不返回任何东西,而且你也没有任何选择。如果它有一个返回值,而且你有权利选择你自己的返回型别(return   type),编译器势必得通过某种方式来知道如何处理那个返回值。”

构造方法对返回类型没有选择权,也就是说不加任何返回修饰符,以示与其他的方法的区别 ,而void类型表示函数可以控制不让返回值,

《Thinking in C++》给的答案 
   Both the constructor and destructor are very unusual types of functions: they have no return value. This is distinctly different from a void return value, in which the function returns nothing but you still have the option to make it something else. Constructors and destructors return nothing and you don’t have an option. The acts of bringing an object into and out of the program are special, like birth and death, and the compiler always makes the function calls itself, to make sure they happen. If there were a return value, and if you could select your own, the compiler would somehow have to know what to do with the return value, or the client programmer would have to explicitly call constructors and destructors, which would eliminate their safety.

简单来说有return就代表着有选择权,即使是void,编译器调用构造函数只是确定它发生,如果有返回值的话编译器就不得不知道针对返回值该这么去做,还有程序员亦可以随意调构造函数了,这样会威胁到程序的安全

额怎么感觉不透彻呢,一定跟编译器的原理有关,等翻翻龙书去


0 0
原创粉丝点击