2016-11-25 67 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

相關問題