构造函数可以返回NULL值吗? [英] Can a constructor return a NULL value?

查看:159
本文介绍了构造函数可以返回NULL值吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道构造函数不会返回任何东西,但例如如果我调用 CMyClass * object = new CMyClass()有任何方法使对象为NULL如果构造函数失败?在我的情况下,我有一些图像必须加载,如果文件读取失败,我想它返回null。有什么办法吗?

提前感谢。

I know constructors don't "return" anything but for instance if I call CMyClass *object = new CMyClass() is there any way to make object to be NULL if the constructor fails? In my case I have some images that have to be loaded and if the file reading fails I'd like it to return null. Is there any way to do that?
Thanks in advance.

推荐答案

我同意其他人你应该使用异常,但如果你真的需要使用NULL为某种原因,使构造函数私有和使用工厂方法:

I agree with everyone else that you should use exceptions, but if you do really need to use NULL for some reason, make the constructor private and use a factory method:

static CMyClass* CMyClass::create();

这意味着你不能正常构造实例,这是一个相当大的缺点

This means you can't construct instances normally though, and you can't allocate them on the stack anymore, which is a pretty big downside

这篇关于构造函数可以返回NULL值吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆