如何处理构造函数中的错误值? [英] How to handle incorrect values in a constructor?

查看:40
本文介绍了如何处理构造函数中的错误值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请注意,这是关于构造函数的问题,而不是关于处理时间的类.

假设我有一个这样的类:

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:

  1. 让构造函数抛出异常,并在调用函数中使用处理程序来处理它.
  2. 在类中有一个标志,只有在构造函数可接受值时才将其设置为 true,并让程序在构造后立即检查标志.
  3. 在调用构造函数之前立即调用一个单独的(可能是静态的)函数来检查输入参数.
  4. 重新设计该类,使其可以从任何输入参数构建.

以下哪种方法在工业中最常见?或者我可能遗漏了什么?

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++.

这篇关于如何处理构造函数中的错误值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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