如何在构造函数中处理不正确的值? [英] How to handle incorrect values in a constructor?

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

问题描述

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

Please note that this is asking a question about constructors, not about classes which handle time.

假设我有一个类:

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);
};

虽然我想要一个构建成功,我想要b的构造函数失败。 / p>

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. 重新设计类,以便可以从任何输入参数构造。 li>
  1. have the constructor throw an exception, and have handlers in the calling function to handle it.
  2. have a flag in the class and set it to true only if the values are acceptable by the constructor, and have the program check the flag immediately after construction.
  3. have a separate (probably static) function to call to check the input parameters immediately before calling the constructor.
  4. redesign the class so that it can be constructed from any input parameters.

以下哪种方法在工业中最常见?

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天全站免登陆