Как обрабатывать неправильные значения в конструкторе?

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

Хотя я хотел бы, чтобы a был успешно создан, я бы хотел, чтобы конструктор b потерпел неудачу.

Time a = Time(12,34,56);
Time b = Time(12,34,65); // second is larger than 60

Однако это невозможно, поскольку конструкторы не возвращают никаких значений и всегда будут успешными.

Как конструктор скажет программе, что она не счастлива? Я подумал о нескольких методах:

have the constructor throw an exception, and have handlers in the calling function to handle it. 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. have a separate (probably static) function to call to check the input parameters immediately before calling the constructor. redesign the class so that it can be constructed from any input parameters.

Какой из этих методов наиболее распространен в промышленности? Или я что-то пропустил?

Ответы на вопрос(11)

Ваш ответ на вопрос