簡體   English   中英

用文件初始化靜態成員

[英]initialize a static member with a file

我有一個字典課,用於拼寫檢查。 我有一個數組作為單詞列表,我必須用一個包含單詞的文件對其進行初始化。 我的問題是,我需要我的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];
        }
    }

有許多方法可以解決編程問題。

這是我的建議:

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實例。

暫無
暫無

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

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