初始化对象时引发错误
Throwing an error when initializing an object
假设在初始化宠物类时,我想排除或禁止狗或猫作为物种。抛出invalid_argument异常的正确方法是什么?
#include <string>
using std::string;
#include <stdexcept>
using std:: invalid_argument;
struct Pet {
const string name;
long age = 0;
const string species;
//Pet()= default;
Pet(): name("CrashDown"),age(0),species("ferret") {};
Pet(const string & the_name, const string & the_species): name(the_name), age(0),
species(the_species) {};
};
如果你有一组特定的物种,我会这样做的方式是使用该物种的枚举:
enum class Species {
horse,
lizard,
human
};
然后使你的班级的物种类型Species
.这会将传递到构造函数的内容限制为"批准的"物种(即,您包含在enum
中的物种(。这只有在您拥有有限(且详尽(的物种列表时才有效。
如果您希望物种不是详尽的,则可能需要一个Species
基类并创建具体的物种子类。然后,您可以使用模板限制特定类型,这将是编译错误而不是异常 - 更可取!
如果你不喜欢这些选项中的任何一个,你可以选择最严格和最容易出错的方法,即检查构造函数主体中的字符串相等性,并在你得到猫、狗或任何其他不受欢迎的物种的情况下抛出。
Pet(const string & the_name, const string & the_species): name(the_name), species(the_species), age(0)
{
if (species == "cats" || species == "dogs")
throw std::invalid_argument( "received negative value" );
}
相关文章:
- 在c++中尝试对对象数组进行排序时,出现std:bad_alloc错误
- 模板,函数使用错误的构造函数来复制我的对象
- 有没有办法让编译器在我放置字符串而不是 nlohmann::json 对象时抛出错误?
- std::unordered_map 类型对象声明期间出现"field has incomplete type"错误
- 错误:malloc:对象 0x7f9edf504080 的 *** 错误:未分配正在释放的指针
- 从对象C++中的文件读取内容时出现分段错误
- cout 新创建的对象引发运行时错误
- 错误:"释放后使用包装器对象 (WRAPPER_ESCAPE)"
- 使用返回对象的函数处理错误
- 创建 QtChart 对象会在运行时创建EXC_BAD_ACCESS错误
- 错误:无法传递非平凡类型"std::string"的对象和更多错误
- 该对象具有与成员函数不兼容的类型限定符.为什么会出现此错误?
- 如何在类模板的成员函数中正确调用函数对象?正在生成 Visual Studio 编译器错误 C2440
- 尝试将对象插入空指针数组时出现分段错误
- 错误:三元运算符无法在对象中正常工作"cout"
- C++:如果括号为空,为什么不抛出错误对象?
- qt vsaddin错误对象引用未设置为对象的istanse
- 如何从函数返回成功或错误对象?
- 复制构造函数错误:对象的类型限定符与成员函数不兼容
- 如何在本机插件中创建node.js错误对象