如果发现传递的参数错误,如何停止对象的构造?

时间:2011-08-04 02:27:08

标签: c++

class Date {
    Date(int day, int month, int year) {
    }
}

int main() {
    Date d = Date(100, 2, 1990);
}

这里传递给day的值(100)不对,我的问题是如何在构造函数中检查'day'参数以防止创建对象

4 个答案:

答案 0 :(得分:11)

抛出异常。

答案 1 :(得分:7)

#include <stdexcept>
#include <iostream>

class Date
{
public:
    Date(int day, int month, int year) {
        if (day < 1 || day > 31) { // oversimplified check!
            throw std::invalid_argument("day");
        }
    }
};

int main()
try
{
    Date d = Date(100, 2, 1990);
}
catch ( const std::exception& error )
{
    std::cerr << error.what() << std::endl;
    return EXIT_FAILURE;
}

答案 2 :(得分:0)

您正在创建自己的“日期”功能。

只需验证构造函数中的参数,如果它们无效就抛出异常。

答案 3 :(得分:-3)

再举一个例子

class base 
{
    public:
       base(int no, int month) 
       {
          p = new int(no);
          // some code
          // now here you have checked value of month and threw exception
       }
private:
    int *p;
};

如果从构造函数抛出异常,则该类的用户必须非常小心以防止内存泄漏。因此,这不是一个好习惯。想以其他方式解决它