构造函数可以返回 NULL 值吗?

编程入门 行业动态 更新时间:2024-10-25 12:26:43
本文介绍了构造函数可以返回 NULL 值吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我知道构造函数不会返回"任何东西,例如如果我调用 CMyClass *object = new CMyClass() 如果构造函数失败,有什么方法可以使 object 为 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 值吗?

本文发布于:2023-11-10 03:08:19,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1574185.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   NULL   值吗

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!