在树中查找节点并替换为具有更新私有成员的新节点

时间:2013-05-30 01:10:40

标签: c++ const binary-tree

我是一个尝试学习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

我的问题是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);
  }

我如何访问“旧”&#39;这个词的数量又增加了一个?我至少走在正确的轨道上? 谢谢你的帮助!

1 个答案:

答案 0 :(得分:2)

您的getCount方法应声明为const

int getCount() const
{
    ...
}

这允许在const个对象(例如currentWord)上调用它。如果方法不改变类的数据,通常应该使它保持不变。这使您可以更灵活地在整个程序中适当地使用const限定符。