我正在创建一个类 User
。我在下面做了一些构造函数重载:
class User
{
public:
explicit User(string firstInit, string secondInit){
this->firstInit = firstInit;
this->secondInit = secondInit;
}//end constructor
explicit User(char firstInit, char secondInit){
this->firstInit = firstInit;
this->secondInit = secondInit;
}//end constructor
explicit User(string firstInit, char secondInit){
this->firstInit = firstInit;
this->secondInit = secondInit;
}//end constructor
explicit User(char firstInit, string secondInit){
this->firstInit = firstInit;
this->secondInit = secondInit;
}//end constructor
};
我的问题与构造函数重载有关。在这种情况下,我是否需要提供构造函数的所有 4 个示例以满足以下要求:
An initial can be a string or character. It does not matter. But account for all cases where a user may enter one or the other.
对于“最佳实践”,我是否满足要求?或者有没有办法声明一个只有 string
和 char
的 enum
并且每个变量必须是那些 enum
之一>?
最佳答案
因此,您有一个 char
或整个 std::string
。由于 std::string
也可用于保存单个 char
,因此我建议使用以下内容:
class User
{
private:
std::string first;
std::string second;
public:
explicit User(std::string firstInit, std::string secondInit) :
first(firstInit),
second(secondInit)
{
//Only this constructor actually initializes any variables.
}
explicit User(char firstInit, char secondInit) : User(std::string({ firstInit }), std::string({ secondInit }))
{
}
explicit User(std::string firstInit, char secondInit) : User(firstInit, std::string({ secondInit }))
{
}
explicit User(char firstInit, std::string secondInit) : User(std::string({ firstInit }), secondInit)
{
}
};
这也使用构造函数委托(delegate),以防您需要更复杂的初始化逻辑,而您不想从头重复一遍。
作为解释:std::string({ firstInit })
将用一个字符创建 std::string
。
关于c++ - 两种类型的构造函数重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58581279/