【问题标题】:Initialize a const field in constructor but first check one parameter在构造函数中初始化一个 const 字段,但首先检查一个参数
【发布时间】:2016-11-25 10:37:26
【问题描述】:

好的,这是我在测试中的一项任务。 您需要使用 const int userID 创建一个 User 类,以便每个 User 对象都有一个唯一的 ID。

我被要求用 2 个参数重载构造函数:键、名称。如果密钥为 0,则用户将拥有唯一 ID,否则用户将获得 userID = -1。

我已经这样做了:

class User{
private:
    static int nbUsers;
    const int userID;
    char* name;
public:
    User(int key, char* name) :userID(nbUsers++){
        if (name != NULL){
            this->name = new char[strlen(name) + 1];
            strcpy(this->name);
        }
    }

};

我不知道如何先检查key参数是否为0,然后初始化const userID。 有什么想法吗?

【问题讨论】:

    标签: c++ constructor constants unique-id


    【解决方案1】:

    可以使用ternary operator,这样就可以在构造函数初始化列表中直接调用:

    class User
    {
    private:
        static int nbUsers;
        const int userID;
        char* name;
    
    public:
        User(int key, char* name) : userID(key == 0 ? -1 : nbUsers++)
        {
            // ...
        }
    };
    

    standard guarantees that only one of the branches will be evaluated,所以nbUserskey == 0 时不会增加。


    或者,您可以使用辅助函数:

    int initDependingOnKey(int key, int& nbUsers)
    {
        if(key == 0) return -1;
        return nbUsers++;
    }
    
    class User
    {
    private:
        static int nbUsers;
        const int userID;
        char* name;
    
    public:
        User(int key, char* name) : userID(initDependingOnKey(key, nbUsers))
        {
            // ...
        }
    };
    

    【讨论】:

    • 赞成,但我更喜欢key ? nbUsers++ : -1。也可以考虑使用static std::atomic<unsigned> ubUsers
    • initDependingOnKey 成为User 类的静态函数会更好!
    猜你喜欢
    • 1970-01-01
    • 2010-11-28
    • 2011-03-28
    • 2011-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-05
    相关资源
    最近更新 更多