gpt4 book ai didi

c++ - 使用文件初始化静态成员

转载 作者:行者123 更新时间:2023-11-28 05:52:24 28 4
gpt4 key购买 nike

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

最佳答案

有很多方法可以解决编程问题。

这是我的建议:

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

关于c++ - 使用文件初始化静态成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34957532/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com