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

suk*_*mar 1 c++

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

int main() {
    Date d = Date(100, 2, 1990);
}
Run Code Online (Sandbox Code Playgroud)

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

Jam*_*lis 11

抛出一个例外.

  • 确实很激烈.所有OP想要的是防止对象创建,而不是破坏他的整个过程. (3认同)

And*_*ron 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;
}
Run Code Online (Sandbox Code Playgroud)