2016-11-25 63 views
0

好的,所以这是我在测试中的一项任务。 您需要使用const int userID创建一个类User,以便每个User对象都有一个唯一的ID。在构造函数中初始化一个const字段,但首先检查一个参数

我被要求用2个参数重载构造函数:key,name。如果密钥为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); 
     } 
    } 

};

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

回答

4

可以使用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,所以nbUsers不会,如果key == 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)) 
    { 
     // ... 
    } 
}; 
+1

Upvoted,但我更喜欢'键? nbUsers ++:-1'。还请考虑使用'静态std ::原子 ubUsers' – Bathsheba

+0

我已经得到它了。非常感谢! – Arkenn

+1

将'initDependingOnKey'作为'User'类的静态函数会更好! – jpo38

相关问题