c++ - 两种类型的构造函数重载

标签 c++ c++11

我正在创建一个类 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.

对于“最佳实践”,我是否满足要求?或者有没有办法声明一个只有 stringcharenum 并且每个变量必须是那些 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/

相关文章:

c++ - 数组损坏其字符 C++

c++ - 为什么右值引用变量不是右值?

c++ - 使用 boost asio 异步读取文件

python - 在 pybind11 (C++) 中使用内置的 "open"python 方法?

c++ - 加倍加倍是否会导致0.0?如果没有,该如何实现?

c++ - 对于循环窃听?

c++ - 如何组合加密哈希?

c++ - 包装类的完美转发

c++ - 我可以在 std::function 中使用模板类型 T 来传递 lambda 类型函数 C++11 吗?

C++11 std::forward 一个指针