初始化对象时引发错误

Throwing an error when initializing an object

本文关键字:错误 对象 初始化      更新时间:2023-10-16

假设在初始化宠物类时,我想排除或禁止狗或猫作为物种。抛出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" );
  }