gpt4 book ai didi

c++ - 检查 ctor 参数的最优雅且不易出错的方法

转载 作者:行者123 更新时间:2023-11-30 00:52:16 25 4
gpt4 key购买 nike

给定以下 person 类的简单构造函数声明:

Person(const string& _firstName, const string& _lastName, const string& _id);

哪种方式被认为是优雅且不易出错以确保给定参数有效?假设我想确保 PERSON 类型的对象将包含空字符串,即使只有一个给定参数无效。我想出了这个解决方案:

Person::Person(const string& _firstName, const string& _lastName, const string& _id) {
if (!isValidName(_firstName) || !isValidName(_lastName)) {
firstName = ""; lastName = ""; id = "";
throw InvalidNameException();
}
if (!isValidID(_id)) {
firstName = ""; lastName = ""; id = "";
throw InvalidIDException();
}
firstName = _firstName;
lastName = _lastName;
id = _id;
}

ctor 现在对我来说太臃肿了,我想过写一个 init 方法,但我不太喜欢那个解决方案。

很想听听一些建议。

最佳答案

我建议在初始化列表中初始化您的成员变量,然后检查它们是否有效。如果不是,则抛出异常。

Person::Person(const string& _firstName, const string& _lastName, const string& _id) : 
firstName( _firstName ),
lastName( _lastName ),
id( _id )
{
if (!isValidName( firstName ) || !isValidName( lastName ) || !isValidID( id ) ) {
throw InvalidNameException();
}

您的成员变量在您进入构造函数主体之前已初始化。问题中的代码会将成员变量初始化为空,然后在分配给它们时再次初始化它们。

通过抛出异常,对象无论如何都不会被认为是被构造出来的,所以你不需要“清除”成员变量。在抛出异常之前成功构造的任何成员变量都将调用其析构函数。请注意,如果您的对象抛出异常,则通过抛出,它不会调用其析构函数(因为它从未完全创建)。

关于c++ - 检查 ctor 参数的最优雅且不易出错的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19455565/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com