How to handle incorrect values in a constructor?(如何处理构造函数中的错误值?)
问题描述
请注意,这是关于构造函数的问题,而不是关于处理时间的类.
假设我有一个这样的类:
Suppose I have a class like this:
class Time
{
protected:
unsigned int m_hour;
unsigned int m_minute;
unsigned int m_second;
public:
Time(unsigned int hour, unsigned int minute, unsigned int second);
};
虽然我希望 a 构造成功,但我希望 b 的构造函数失败.
While I would want a to be constructed successfully, I would want the constructor of b to fail.
Time a = Time(12,34,56);
Time b = Time(12,34,65); // second is larger than 60
然而,这是不可能的,因为构造函数不返回任何值并且总是会成功.
However, this is not possible, because constructors do not return any values and will always succeed.
构造函数如何告诉程序它不开心?我想到了几个方法:
How would the constructor tell the program that it is not happy? I have thought of a few methods:
- 让构造函数抛出异常,并在调用函数中使用处理程序来处理它.
- 在类中有一个标志,只有在构造函数可接受值时才将其设置为 true,并让程序在构造后立即检查标志.
- 在调用构造函数之前立即调用一个单独的(可能是静态的)函数来检查输入参数.
- 重新设计该类,使其可以从任何输入参数构建.
以下哪种方法在工业中最常见?或者我可能遗漏了什么?
Which of these methods is most common in industry? Or is there anything I may have missed?
推荐答案
典型的解决方案是抛出异常.
The typical solution is to throw an exception.
其背后的逻辑如下:构造函数是一种将内存块转换为有效对象的方法.要么它成功(正常完成)并且您有一个有效的对象,要么您需要一些不可忽视的问题指示符.异常是使问题在 C++ 中不可忽略的唯一方法.
The logic behind that is the following: the constructor is a method that transforms a chunk of memory into a valid object. Either it succeeds (finishes normally) and you have a valid object or you need some non-ignorable indicator of a problem. Exceptions are the only way to make the problem non-ignorable in C++.
这篇关于如何处理构造函数中的错误值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何处理构造函数中的错误值?


基础教程推荐
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- Windows Media Foundation 录制音频 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 从 std::cin 读取密码 2021-01-01