是否有一种方法可以防止在构造函数中构造对象
Is there a way to prevent the object from construct in the constructor?
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;
}
}
我在这里找到一个资源,如果发现传递的参数是错误的,如何阻止类的对象构造?有没有办法做到毫无例外?是否有一种方法可以让构造函数检查参数本身并销毁它自己?
我建议这样做
Date::Date(int InputDay, int InputMonth, int InputYear) {
if (!CheckDate(InputDay, InputMonth, InputYear))
throw "Date Invalid!n"; // throw exception
else {
Day = InputDay;
Month = InputMonth;
Year = InputYear;
}
}
另外,使用try-catch
块捕获异常,并将CheckDate
声明为static
。
正如Jerry Coffin所说,除了抛出异常之外,没有合适的方法来停止对象的构造。
唯一的选择是在你的类中有一个布尔值(valid
),调用者应该在创建和删除(或重置或其他)之后测试它,如果它是假的。但是它依赖于调用者做正确的事情,而不是在类本身中处理错误条件。
异常有这个特殊的值:调用者可以捕捉到它们,如果他想,但如果他不在乎,异常确保一个构造不好的对象不会被无意中使用。
你不能在Check Date函数中调用->~Date()。在类Date函数中,一个类不能在它的函数中解构自己,它只能使用它的类。如果检查失败,可以抛出异常,不要解构类。
正如Matt所说,引发一个异常。
在另一种情况下,您可以使用指针。考虑date类对于用户是什么样子的。
...
Date due(a,b,c);
...
如果您中途退出,则无法判断due是否无效。唯一的方法是抛出异常。
另一种方法(使用unique_ptr包装器)是创建一个函数:unique_ptr<Date> due=makeDate(d,m,y)
unique_ptr<Date> makeDate(int d,int m,int y)
{
if( CheckDate(d,m,y)) // make your Checkdate function static.
return make_unique<Date>(d,m,y);
else
return make_unique<Date>(nullptr);
}
仔细检查这里的所有内容,我的unique_ptr语义还没有达到标准:)
相关文章:
- 对象实例化调用构造函数的次数太多
- Arduino C++在构造函数中用参数声明对象数组
- 模板,函数使用错误的构造函数来复制我的对象
- 我使用向量来创建类对象列表.初始化向量时如何使用参数调用构造函数?
- std::vector::p ush_back() 不会在 MSVC 上编译具有已删除移动构造函数的对象
- 通过构造函数创建的所有对象都具有相同的向量
- 是什么让放置新调用对象的构造函数?
- 复制包含C++所有元素的对象!(构造函数和赋值,最佳实践?
- C++ 对象指针数组的复制构造函数
- 在构造函数中输入对象时C++类成员作用域
- C++:将初始化的对象传递给另一个类的构造函数;需要不必要的构造函数吗?
- 这个C++编译器优化(在自身的实例上调用对象自己的构造函数)的名称是什么,它是如何工作的?
- 如何从构造函数副本 T(const T&)调用对象 T?
- 将另一个类的对象传递到当前类C++的构造函数中(不是成员初始化)
- 如何将我编写的对象传递到另一个类的构造函数中?
- 使用向量初始化参数化构造函数的对象数组
- 在C++中将对象从另一个类传递到另一个类的构造函数?
- 在 C++ 中声明 const 对象需要用户定义的默认构造函数.如果我有一个可变成员变量,为什么不呢?
- 构造函数对象赋值是否泄漏内存
- gcc中不可移动构造函数对象的std::函数