2017-06-15 22 views
0

私のコンストラクタは1つの変数だけを取ると仮定しています。しかし、コンストラクタの定義にない他の変数を初期化することは興味深いです。コンストラクタコンストラクタ内で初期化とプライベート変数を設定する

class WordAnalysis{ 
private: 
    int timesDoubled; 
    word *words; 
    int wordCount; 
    int index; 
    void doubleArrayAndAdd(string); 
    bool checkIfCommonWord(string); 
    void sortData(); 
public: 
    bool readDataFile(char*); //returns an error if file not opened 
    int getWordCount(); 
    int getUniqueWordCount(); 
    int getArrayDoubling(); 
    void printCommonWords(int); 
    void printResult(int); 
    WordAnalysis(int); 
    ~WordAnalysis(); 

}

例:WordAnalysisのどのインスタンスでも、現在の倍率は0になりますか?ゲッター関数はセッターなしでこの情報を取得できますか?

WordAnalysis::WordAnalysis(int arrSize){ 

wordCount = arrSize; 
int timesDoubled = 0; 
int index = 0; 
} 
+2

[良い本](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list)を拾い読みして読むことをお勧めします。 –

答えて

2

はいさて、あなたはそれが対応する引数を取らない場合でも 、コンストラクタ内の他のメンバ変数を初期化することができます。

しかし、例では、上記与えた:

WordAnalysis::WordAnalysis(int arrSize){ 

wordCount = arrSize; 
int timesDoubled = 0; 
int index = 0; 
} 

あなたが実際にtimesDoubledメンバ変数を初期化していない、あなたは新しい変数を宣言してにそれを設定され、その前に「INT」を書いたので、 0

あなたが書かなければならないクラスtimesDoubled変数を設定したい場合:

timesDoubled = 0; 

それともあなたはそれについてより明確になりたい場合は、あなたが電子できます書記:

WordAnalysis::timesDoubled = 0; 
+0

これを理解するのに何時間も費やしましたが、それ以前にintを削除するのは簡単でした。親切にしてくれてありがとうございます! –

1

はい。あなたはできる。しかし、宣言時にデータメンバーのクラス内初期化を行うことができます。必要なデータメンバを初期化するには、コンストラクタにinitializer listを使用する必要があります。すべてのデータメンバーは、コンストラクター内で表示されます。それらの値を割り当てることができます。技術的には、initializer listを使用すると初期化され、代入演算子(=)が使用されている場合はassignmentになります。

ここだが、コメントであなたのコードの抜粋です:

class WordAnalysis 
{ 
private: 

    // Data member initialization on declaration 

    int timesDoubled { 0 }; 
    word* words   { nullptr }; 
    int wordCount  { 0 }; 
    int index   { 0 }; 

public: 

    // Initializing timesDoubled using initializer list 

    WordAnalysis(const int t) : timesDoubled{ t } 
    { 
     // Assign default values here if need be 

     index = 10; // assignment 
    } 

    // ... 
}; 

あなたのコンパイラは、データメンバーの中に、クラスの初期化を可能にするために、少なくともC++11 compliantでなければなりません。

1

私は、次のようなデフォルトコンストラクタを定義示唆:クラスのすべてのインスタンスが初期化されるような方法

WordAnalysis() 
{ 
    timesDoubled = 0; 
    words[0] = '\0'; //assuming it's an array of char 
    wordCount = 0; 
    index = 0; 
} 

を。

関連する問題