[英]initialize a static member with a file
I have a dictionary class , for spell checking . 我有一个字典课,用于拼写检查。 I have an array as the list of words , and I must initialize it with a file that there are words in it .
我有一个数组作为单词列表,我必须用一个包含单词的文件对其进行初始化。 my problem is that , I need my wordlist variable to be a static variable , cause only one of it is enough for any other extra object created from the dictionary class and it is logical , however there is no need for a second object of the class , but what if we needed more than one object?
我的问题是,我需要我的wordlist变量是一个静态变量,因为只有其中一个足以满足从字典类创建的任何其他对象,并且它是逻辑上的,但是不需要该类的第二个对象,但是如果我们需要多个对象怎么办? is there a way?
有办法吗?
#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 must be static ... 单词表必须是静态的...
I only can think of this kind of defining ... 我只能想到这种定义...
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];
}
}
There are many ways to solve the programming problem. 有许多方法可以解决编程问题。
Here's my suggestion: 这是我的建议:
Move the static
members out of the class. 将
static
成员移出类。
class Dictionary
{
public:
Dictionary();
bool lookUp(const char *)const;
private:
void suggestion(const char *)const;
};
In the .cpp file, use: 在.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");
}
This will make sure that the word list is initialized only once, regardless of how may instances of Dictionary
you create. 这将确保单词列表仅初始化一次,而不管您如何创建
Dictionary
实例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.