类构造函数 c++ 中的条件

Condition in class constructor c++

本文关键字:条件 c++ 构造函数      更新时间:2023-10-16

>我必须编写包含个人数据(例如姓名,姓氏和年龄(的类定义,条件是年龄不能小于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,因为这更惯用且推荐。