【问题标题】:Creating an object of a class with constructor that throws使用抛出的构造函数创建类的对象
【发布时间】:2014-06-12 13:21:15
【问题描述】:

我正在学习异常。示例代码的目的是创建一个适当的对象。 就这样吧……

#include <iostream>
#include <exception>
#include <string>
#include <stdexcept>

using std::string;
using std::invalid_argument;
using std::cin;
using std::cout;
using std::endl;

class Person
{
public:
    Person(){}
    Person(string name, int age)
    {
        if (age < 18)
            throw invalid_argument(name + " is minor!!!");
        if (name.empty())
            throw invalid_argument("Name can't be empty");
        _name = name;
        _age = age;
    }
    Person(Person&& that) : _name(std::move(that._name))
    {
        _age = that._age;
        that._name.clear();
    }
    Person& operator=(Person&& that)
    {
        _name = std::move(that._name);
        _age = that._age;
        that._name.clear();
        return *this;
    }

    Person(const Person& that)
    {
        _age = that._age;
        _name = that._name;
    }
    Person& operator=(const Person& that)
    {
        _name = that._name;
        _age = that._age;
        return *this;
    }

    ~Person() { cout << "In person destructor"; }
    string getName(void) const { return _name; }
private:
    string _name;
    int _age;
};

Person createPerson()
{
    try
    {
        string name;
        int age;
        cout << "Enter name of the person: ";
        cin >> name;
        cout << "Enter age of the person: ";
        cin >> age;
        Person aNewPerson(name, age);
        return aNewPerson;
    }
    catch (invalid_argument& e)
    {
        cout << e.what() << endl;
        cout << "Please try again!!!" << endl;
    }
}

int main(void)
{
    Person aNewPerson;

    aNewPerson = createPerson();

    cout << aNewPerson.getName() << " created" << endl;

    return 0;
}

我只想在构造正确的对象时退出程序。 例如,如果我输入名称为 APerson,年龄为 1,则会引发异常。 但是,我想继续创建对象的过程,只有在成功创建对象后才退出程序。

我不知道该怎么做。 有人可以帮忙吗? 谢谢。

【问题讨论】:

  • 为了无限次地做某事,你需要某种循环。
  • 没错。另外,我是否在正确的地方处理异常?因为如果构造函数抛出异常,createPerson() 不会返回任何内容。我不知道如何继续......
  • 您需要先添加循环。如果 CreatePerson 到那时还不能神奇地自行修复,那么您可能将循环添加到错误的位置。

标签: c++ exception c++11


【解决方案1】:

好的,我得到了答案,如果我错了,请纠正我...... 我像这样修改了 createPerson() 函数...

Person createPerson()
{
    while (1)
    {
        try
        {
            string name;
            int age;
            cout << "Enter name of the person: ";
            cin >> name;
            cout << "Enter age of the person: ";
            cin >> age;
            Person aNewPerson(name, age);
            return aNewPerson;
        }
        catch (invalid_argument& e)
        {
            cout << e.what() << endl;
            cout << "Please try again!!!" << endl;
        }
    }
}

【讨论】:

  • 没错。您可以更改的一件事是在 cin &gt;&gt; age; 之后和 Person 构造函数之前进行尝试,以便更好地可视化可能发生异常的位置。
猜你喜欢
  • 2017-01-28
  • 1970-01-01
  • 2017-12-04
  • 2013-09-23
  • 1970-01-01
  • 2016-09-23
  • 2019-07-25
  • 2023-03-21
  • 1970-01-01
相关资源
最近更新 更多