我是一个试图学习c ++的新手。我正在编写一个程序,试图计算一个单词在文本字段中出现的次数我的程序正在将类的元素存储word
在 bintree 中。Word
类有两个私有成员:代表文本文件单词的字符串和计数。如果一个单词已经存在,我必须将计数加一
class word {
private:
string myWord;
int count;
public:
word(): myWord(""), count(1)
{
}
word(string input): myWord(input), count(1)
{
}
<ovreload operators>
<some methods>
void addCount(int oldCount)
{
count += oldCount;
}
int getCount()
{
return count;
}
};
然后在一个将被调用的方法中,main
我试图找出这个词是否已经存在并添加计数:
void removeSeparators(string input, bintree<word> &tree, int &count)
{
removeDot(input);
word * pword;
const word * currentWord;
int currCount = 0;
<use tokenizer to separate each word>
// if the tree find the word
if(tree.find(*pword) != NULL) {
//get the current word
currentWord = tree.find(*pword);
//get the current count of the word
currCount = currentWord -> getCount(); <--- ERROR line 175
pword -> addCount(currCount);
//erase the old node
tree.erase(*currentWord);
//insert new node
tree.insert(*pword);
this is the total count of words
count++; }
if(tree.find(*pword) == NULL) { tree.insert(*pword); count++; }
<bit more code for resetting tokanizer>
}
这是我的错误:countWords.cpp: In function ‘void removeSeparators(std::string, bintree<word>&, int&)’:
countWords.cpp:175: error: passing ‘const word’ as ‘this’ argument of ‘int word::getCount()’ discards qualifiers
我的问题是 find 方法tree
如下所示,我无法更改:
const dataType* find(const dataType &findData) const
{
// this function looks for findData in the tree.
// If it finds the data it will return the address of the data
// in the tree. otherwise it will return NULL
if (root == NULL) return NULL;
else return root->find(findData);
}
如何访问单词的“旧”计数并加一?我至少在正确的轨道上?谢谢您的帮助!