Can a constructor return a NULL value?(构造函数可以返回 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 值吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:构造函数可以返回 NULL 值吗?
基础教程推荐
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- CString 到 char* 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
