关于构造函数没有返回值的问题
来源:互联网 发布:守望先锋生涯数据查询 编辑:程序博客网 时间: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,编译器调用构造函数只是确定它发生,如果有返回值的话编译器就不得不知道针对返回值该这么去做,还有程序员亦可以随意调构造函数了,这样会威胁到程序的安全
额怎么感觉不透彻呢,一定跟编译器的原理有关,等翻翻龙书去
- 关于构造函数没有返回值的问题
- 关于构造函数没有返回值的问题
- 关于Javascript中构造函数返回值的问题
- 构造函数有没有返回值的总结
- java构造函数有没有返回值的总结
- 构造函数真的没有返回值吗?
- 为什么构造函数没有返回值?
- 构造函数有没有返回值
- 为什么构造函数没有返回值?
- 构造函数有没有返回值?
- 构造函数为什么没有返回值
- 构造函数有没有返回值?
- Android构造函数有没有返回值?
- 构造函数返回值问题
- 构造函数析构函数为什么没有返回值?
- 构造函数和析构函数为何没有返回值
- 构造函数析构函数为什么没有返回值?
- 构造函数析构函数为什么没有返回值?
- 类的继承
- 听说王铮亮要给主席送专辑?
- grade 3 class 2, half 1
- 秒杀项目的注意事项
- 河滩小螃蟹部分代码
- 关于构造函数没有返回值的问题
- pu ke didi
- 设计模式(12) 代理模式(PROXY)
- double badminton match
- VC和GCC静态变量析构顺序不同
- 关于fstream修改文件内容的操作
- 类 的继承2
- 解bug的心得
- 【面向对象设计模式】 接口型模式 (一)