C++ Constructors have no return type. Just exactly why?(C++ 构造函数没有返回类型.究竟是为什么?)
问题描述
我在 Google 上搜索过这个问题并阅读了很多帖子,但是有很多不同的答案,所有这些都合乎逻辑,我想知道该主题的专家是否可以揭开这个问题的神秘面纱.
I've Googled this and read many posts, but there are so many different answers that all make logical sense that I was wondering if an expert on the topic could demystify this question.
有人说没有返回是因为没有办法返回——语法禁止它——是的,这是有道理的,但我相信所有函数都必须返回一些东西,不是吗?其他人说构造函数会返回新创建的对象本身,这似乎是有道理的,因为在构造函数上使用了赋值运算符.还有一些人有其他有趣的解释.
Some say that there is no return because there is no way to return - the syntax prohibits it - yes, this makes sense, but I believe that all functions have to return something, no? Others say that the constructor sort of returns the newly created object itself, which seems to make sense since the assignment operator is used on the constructor. Still others have other interesting explanations.
推荐答案
构造函数不像其他函数那样被调用,所以它们不会像其他函数那样返回.它们作为某些构造的副作用执行(转换、new、变量定义、ctor-initializer-list、按值传递、按值返回).
Constructors aren't called like other functions, so they don't return like other functions. They execute as a side-effect of certain constructs (cast, new, variable definition, ctor-initializer-list, pass-by-value, return-by-value).
这篇关于C++ 构造函数没有返回类型.究竟是为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C++ 构造函数没有返回类型.究竟是为什么?
基础教程推荐
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- CString 到 char* 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
