2016-01-22 78 views
0

我有一個字典類,用於拼寫檢查。我有一個數組作爲單詞列表,我必須用一個有文字的文件來初始化它。 我的問題是,我需要我的wordlist變量是一個靜態變量,導致只有一個是足夠的從字典類創建任何其他額外的對象,這是合乎邏輯的,但是不需要第二個對象的類,但如果我們需要多個對象呢?有沒有辦法?使用文件初始化靜態成員

#ifndef DICTIONARY_H 
#define DICTIONARY_H 

class Dictionary 
{ 
public: 
    static const int SIZE = 109582; 
    Dictionary(); 
    bool lookUp(const char *)const; 
private: 
    void suggestion(const char *)const; 
    char *wordList[SIZE]; 
}; 

#endif 

單詞表必須是靜態的......

我只能認爲這種定義的...

Dictionary::Dictionary() 
    { 
     ifstream inputFile("wordsEn.txt", std::ios::in); 

     if (!inputFile) 
     { 
      cerr << "File could not be opened." << endl; 
      throw; 
     } 

     for (int i = 0; i < SIZE && !inputFile.eof(); ++i) 
     { 
      wordList[i] = new char[32]; 
      inputFile >> wordList[i]; 
     } 
    } 
+0

這個主題可能有一些其他的變化,但是,這就是你必須做的。它需要在循環中讀取文件並放入列表中。 –

+0

這是真的,但它是浪費時間和記憶,有多個詞列表@MatsPetersson – shayan

+0

我不明白爲什麼你需要多個字典,反正。 –

回答

1

有很多方法來解決規劃問題。

這裏是我的建議:

移動的static成員出班。

class Dictionary 
{ 
    public: 
     Dictionary(); 
     bool lookUp(const char *)const; 
    private: 
     void suggestion(const char *)const; 
}; 

在.cpp文件,使用:

static const int SIZE = 109582; 
static std::vector<std::string> wordList(SIZE); 

static int initializeWordList(std::string const& filename) 
{ 
    // Do the needul to initialize the wordList. 
} 

Dictionary::Dictionary() 
{ 
    static int init = initializeWordList("wordsEn.txt"); 
} 

這將確保該單詞列表被初始化的,無論你創建Dictionary怎麼可能情況下只有一次。

+0

如何將單詞列表作爲獨立的數據類型?然後用它作爲靜態? – shayan

+0

如果您需要標準庫未提供的任何功能,則可以這樣做。 –