2014-10-19 68 views
0

所以我在嘗試插入到二叉搜索樹時遇到了這些錯誤,我幾乎不知道該怎麼做,並且幾乎不能找到任何東西互聯網幫助提前謝謝。C++ BinarySearchTree插入一個元素

In file included from Indexer.h:19, 
       from Indexer.cpp:20: 
BinarySearchTree.h: In member function ‘void BinarySearchTree<Comparable>::insert(const Comparable&, BinarySearchTree<Comparable>::BinaryNode*&) [with Comparable = Word]’: 
BinarySearchTree.h:108: instantiated from ‘void BinarySearchTree<Comparable>::insert(const Comparable&) [with Comparable = Word]’ 
Indexer.cpp:109: instantiated from here 
BinarySearchTree.h:165: error: passing ‘const Word’ as ‘this’ argument of ‘bool Word::operator<(Word&)’ discards qualifiers 
BinarySearchTree.h:167: error: no match for ‘operator<’ in ‘t->BinarySearchTree<Word>::BinaryNode::element < x’ 
Word.h:33: note: candidates are: bool Word::operator<(Word&) 
make: *** [Indexer.o] Error 1 

而且我認爲是創造它是從Indexer.cpp線109

字需要兩個參數,電流爲字符串並計數碼等於0,這一功能。

Indexer.cpp 

      BinarySearchTree<Word> filterTree; 
    Line 109: filterTree.insert(Word(current, count)); 


BinarySearchTree.h 

    void insert(const Comparable & x) 
    { 
    Line:108 insert(x, root); 
    } 

Word.cpp :operator< 

bool Word::operator<(Word &RHS) 
{ 
    if(m_wordText < RHS.GetWord()) 
    { 
     return true; 
    } 
    else 
    return false; 
} 
+1

如果函數返回直接成員變量(而不是本地變量)和型很大,您可以將返回類型更改爲const引用,以實現小的性能提升。例如'const string&Word :: GetWord()const' – 2014-10-19 01:36:10

回答

0

會員比較應該(幾乎)總是const函數採取const參數,

bool Word::operator<(Word const&) const; 

任何稱爲const函數內部功能也必須const本身

std::string Word::GetWord() const; 

(如@NeilKirk正確地指出這應該可能返回std::string const&)。

您應該瞭解const的正確性,因爲它可以阻止您在代碼中犯下愚蠢的錯誤。

另外使用非成員比較器通常是優選的,因爲它允許表達的兩側使用的轉換運算符

bool operator<(Word const& lhs, Word const& rhs) 
{ 
    return lhs.GetWord() < rhs.GetWord(); 
}