类构造函数 c++ 中的条件
Condition in class constructor c++
>我必须编写包含个人数据(例如姓名,姓氏和年龄(的类定义,条件是年龄不能小于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("托马斯"、"某物",-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
,因为这更惯用且推荐。
相关文章:
- 为什么"do while"循环不断退出,即使条件计算结果为 false?
- 在没有太多条件句的情况下,我如何避免被零除
- 基于多个条件处理地图中的所有元素
- 条件constexpr函数
- 无论条件是否为true,if总是在c++中执行
- 我可以使用条件运算符初始化C风格的字符串文字吗
- 基于模板值的条件变量
- 多个If语句与使用逻辑运算符计算条件的单个语句的比较
- 将按位if条件转换为普通if条件
- 条件断点在不应该触发时触发
- 为什么简单的算术减法在"if"条件下不起作用?
- 如何在for循环中包含两个索引值的测试条件
- 如果条件为TRUE(最佳方式?),则在do while循环中后置增量
- 我提出什么条件才能再加5%的折扣
- 循环中的条件:为什么每次都调用strlen(),而vector.size()只调用一次
- 即使没有满足他们的条件,我也无法通过一些 do-while 循环
- 如何编写一个使用n倍三元条件语句的C++布尔函数
- 没有超时的C++条件变量
- 正在LLVM中检测整数比较条件
- 在条件变量中触发错误信号的频率是多少