【发布时间】:2015-10-11 19:38:37
【问题描述】:
class Date
{
private:
int Day;
int Month;
int Year;
bool CheckDate(int InputDay, int InputMonth, int InputYear);
// this return true when the date is valid
public:
Date(int InputDay, int InputMonth, int InputYear);
~Date();
};
Date::Date(int InputDay, int InputMonth, int InputYear)
{
if (!CheckDate(InputDay, InputMonth, InputYear))
{
cout << "Date Invalid!\n";
this->~Date();
// this invokes the destructor
// however at the end of the program the destructor would invoke again
}
else
{
Day = InputDay;
Month = InputMonth;
Year = InputYear;
}
}
我在这里找到资源How can object construction of a class be stopped if a parameter passed is found to be wrong?。 有没有办法无一例外地做到这一点? 有没有办法让构造函数检查参数本身并自行销毁?
【问题讨论】:
-
调用者如何检查这个?如果类转换为
bool和/或operator!,则您的代码已经编译并且不正确。如果调用者不检查怎么办? -
没有。事实上,这是向 C++ 添加异常处理的最大动机之一。
-
我会提出一个例外。我不会这样做。
-
抛出异常。这就是他们的目的。
-
@JerryCoffin 谢谢。你的回答是最简单最准确的。
标签: c++ constructor destroy