创建具有抛出构造函数的类的对象
Creating an object of a class with constructor that throws
我正在学习例外。示例代码的目的是创建一个合适的对象。
#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;
}
我希望仅在构造了适当的对象时退出程序。例如,如果我输入name为APerson, age为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;
}
}
}
相关文章:
- 类中的 Arduino 对象构造函数设置垃圾值
- 编译错误:临时对象构造函数中缺少参数
- 双指针在使用 new 时不调用对象构造函数
- 以支持继承的方式将自身shared_ptr添加到对象构造函数中的向量中
- 在创建对象向量时,不为每个对象唯一调用默认对象构造函数
- GCC __attribute__((constructor)) 在对象构造函数之前调用
- 自定义对象构造函数在循环外部循环
- 从全局对象构造函数停止监视器计时器
- Arduino 上的 Sketch 停止在对象构造函数中执行
- 通过在引用线程对象来传递取消引用的“this”指针来在函数对象构造函数中创建线程是好是坏
- 为什么当对象构造函数投入新表达式时,为什么不调用DealLocation函数
- 临时结构对象构造函数奇数调用
- 未显式引用对象的全局对象构造函数在最终二进制文件 - LD 中被丢弃
- 为什么 Clang++ 不在另一个静态库中运行全局对象构造函数?
- 在未加载上下文的情况下在对象构造函数中使用OpenGL函数
- 为什么我们需要一个用户提供的const对象构造函数
- 对象构造函数的C++数组
- 将子结构值设置为对象构造函数中安全的纯虚拟函数返回的值
- C等价于新对象(构造函数)
- C++:直接在参数列表中使用数组文字的对象构造函数