返回信息流我们知道,C++的构造函数是不能任何返回类型的。但是可不可以直接return来结束构造函数呢?像这样:
class test{
public:
test(){
...
if ()
return;
...
}
}
经过测试,这样做是可以的。那么在构造函数中的return与普通函数return返回void有何区别呢?
这是一条镜像帖。来源:北邮人论坛 / cpp / #80123同步于 2014/6/6
该镜像源已超过 30 天没有更新,可能在源站已被删除。
CPP机器人发帖
C++构造函数可不可以return?
xuzhenqi
2014/6/6镜像同步10 回复
订阅后,新回复会通过你的通知中心匿名送达。
9 条回复
是呀,定义构造函数时没有返回值,但是可以使用return来结束函数,是不是很奇怪?
【 在 Lavender0225 的大作中提到: 】
: 定义构造函数时候就没有返回值呀。。干嘛要在里面写return。。
: 发自「佳邮」
你不用return人家照样也可以结束啊,意思就是:5+4+0=9和5+4=9是一样的,你的return也就相当于那个加 0,可有可无(我是这么理解的[ema41])
【 在 xuzhenqi (xuzhenqi) 的大作中提到: 】
: 是呀,定义构造函数时没有返回值,但是可以使用return来结束函数,是不是很奇怪?
通过『我邮2.0』发布
Yes, using return statements in constructors is perfectly standard.
Constructors are functions that do not return a value. The family of functions that do not return a value consists of: void functions, constructors and destructors. It is stated in 6.6.3/2 in the C++ standard. The very same 6.6.3/2 states that it is illegal to use return with an argument in a function that does not return a value.
6.6.3 The return statement
2 A return statement without an expression can be used only in functions that do not return a value, that is, a function with the return type void, a constructor (12.1), or a destructor (12.4). A return statement with an expression of non-void type can be used only in functions returning a value; the value of the expression is returned to the caller of the function.
Additionally, 12.1/12 states that
12.1 Constructors
12 No return type (not even void) shall be specified for a constructor. A return statement in the body of a constructor shall not specify a return value.
See original post at: http://stackoverflow.com/questions/5255777/what-if-i-write-return-statement-in-constructor
很具体,多谢!
【 在 q397273499 的大作中提到: 】
: Yes, using return statements in constructors is perfectly standard.
: Constructors are functions that do not return a value. The family of functions that do not return a value consists of: void functions, constructors and destructors. It is stated in 6.6.3/2 in the C++ standard. The very same 6.6.3/2 states that it is illegal to use return with an argument in a function that does not return a value.
: 6.6.3 The return statement
: ...................