我必须写一个包含个人数据(例如姓名、姓氏和年龄)的类定义,条件是年龄不能小于 1。我试图在类构造函数中捕获异常:
class Person {
public:
Person (std::string name, std::string surname, int age) {
try{
this -> name = name;
this -> surname = surname;
this -> age = age;
if(age < 1)
throw std::string("Error! Age cannot be less than 1!");
}
catch(std::string ex){
cout << ex << endl;
}
};
private:
std::string name;
std::string surname;
int age;
};
这很好用,但最重要的是根本不应该创建年龄 < 1 的对象,而使用这个解决方案我只得到一个错误,对象为 person1("Thomas ", "Something", -5) 仍在创建中。
“阻止”创建不满足条件的对象的最佳方法是什么?
最佳答案
保证您不会创建具有错误值的对象的一种方法是在构造函数中抛出异常,就像您所做的那样。只是不要捕获它,让它被试图创建坏对象的代码捕获:
class Person
{
public:
Person(std::string name, std::string surname, int age) {
if(age < 1)
throw std::string("Error! Age cannot be less than 1!");
this->name = name;
this->surname = surname;
this->age = age;
}
private:
std::string name;
std::string surname;
int age;
};
顺便说一句,更常见的是使用构造函数的初始化列表来初始化变量:
class Person
{
public:
Person(std::string const& name, std::string const& surname, int age)
: name(name), surname(surname), age(age) {
if(age < 1)
throw std::runtime_error("Error! Age cannot be less than 1!");
}
private:
std::string name;
std::string surname;
int age;
};
通过引入构造函数,您可以保证对象在您使用时有效:
int main()
{
try
{
Person p("John", "Doe", -5);
// if we get here the person must be valid
}
catch(std::exception const& e)
{
std::cerr << e.what() << '\n';
return EXIT_FAILURE;
}
}
另请注意,我抛出一个 std::exception派生对象,而不是 std::string
,因为后者更惯用,更值得推荐。
关于c++ - 类构造函数中的条件 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49371758/