2016-11-25 4 views
0

いいえ、これは私がテストで持っていた作業でした。 const User IDを持つUserクラスを作成して、各Userオブジェクトが一意のIDを持つようにする必要があります。コンストラクタでconstフィールドを初期化しますが、最初に1つのパラメータを確認してください

キー、名前の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); 
     } 
    } 

};

最初にキーパラメータが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、そうkey == 0場合nbUsersがインクリメントされることはありません。


また、あなたはヘルパー関数を使用することができます

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'です。 'static std :: atomic ubUsers'を使用することについても考えてみましょう – Bathsheba

+0

私は今それを持っています。どうもありがとう! – Arkenn

+1

'initDependingOnKey'を' User'クラスの静的関数にする方がいいでしょう! – jpo38

関連する問題