簡體   English   中英

類構造函數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(“ 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因為這更慣用和推薦。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM