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'参数以防止创建对象
#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)