C++ 构造函数没有返回类型.究竟是为什么?

C++ Constructors have no return type. Just exactly why?(C++ 构造函数没有返回类型.究竟是为什么?)

本文介绍了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++ 构造函数没有返回类型.究竟是为什么?

基础教程推荐