【问题标题】:initialize a static member with a file用文件初始化静态成员
【发布时间】:2016-01-22 23:16:02
【问题描述】:

我有一个字典类,用于拼写检查。我有一个数组作为单词列表,我必须使用其中包含单词的文件对其进行初始化。 我的问题是,我需要我的 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

wordlist 必须是静态的 ...

我只能想到这种定义……

  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];
        }
    }

【问题讨论】:

  • 这个主题可能还有其他一些变化,但是是的,这就是你必须做的。它需要循环读取文件并将其放入您的列表中。
  • 这是真的,但是拥有多个 wordLists @MatsPetersson 是浪费时间和内存
  • 我不明白你为什么需要不止一本字典。
  • 这是一个“编程问题”,其中“不要那样做”是正确答案。
  • @shayan 1) 你可以使用 std::string 吗? 2) 你想要 1 个静态单词表和 n 个使用相同的字典吗?还是您想要几个大小不变的单词表(例如每种语言 1 个)?

标签: c++ arrays static fstream


【解决方案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 实例如何。

【讨论】:

  • 如何将单词列表作为一个独立的数据类型?然后将其用作静态?
  • 如果您需要标准库未提供的任何功能,您可以使用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-18
  • 2015-05-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多