簡體   English   中英

構造函數初始化和構造函數內部設置的私有變量

[英]Constructor Initialization and private variables set inside constructor

我的構造函數假定僅采用一個變量。 但是我很好奇您是否可以初始化構造函數定義中沒有的其他變量。

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,並且getter函數能夠在不使用setter的情況下獲取此信息?

WordAnalysis::WordAnalysis(int arrSize){

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

是的,即使您不使用相應的參數,也可以在構造函數中初始化其他成員變量。

但是,在上面的示例中:

WordAnalysis::WordAnalysis(int arrSize){

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

您實際上並沒有初始化timesDoubled成員變量,因為您在其之前寫了“ int”,即聲明一個新變量並將其設置為0。

如果要設置classesTimesDoubled變量,則必須編寫:

timesDoubled = 0;

或者,如果您想對此更加明確,甚至可以編寫:

WordAnalysis::timesDoubled = 0;

是。 您可以。 但是,您可以在聲明時對數據成員進行類內初始化。 您應該使用帶有構造函數的初始化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以允許數據成員的類內初始化。

我建議定義一個默認的構造函數,例如:

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

這樣,該類的所有實例將被初始化。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM