2014-10-17 57 views
0

所以基本上我有一個類「句子」#包含「單詞」。你可以切換操作員的邊+

句話也就是說

的鏈表,這裏是我的問題

「字+句子返回添加到開始與Word中的新句」 所以基本上

Word w = "The"; 
Sentence s = "dog jumped high." 
//the object type of w+s should be a sentence 

然而,我得到的錯誤,

'Sentence' does not name a type 
//this is in reference to the return type of overloaded operator+ function, which is in the word class 

S o是否有翻轉操作符的右側和左側的方法+超載,以便我可以將代碼放入Sentence類中。

我不能把代碼中的句子類,因爲有一個單獨的過載保護功能,我需要

s+w 

返回一個句子末尾添加

+2

的問題是,你不能聲明函數返回'Sentence'後才你已經定義了'Sentence'類。爲了避免這個問題,使用非成員操作符重載(無論如何,這是個好主意)。 [看到這裏一個完整的破敗](http://stackoverflow.com/questions/4421706/operator-overloading) – 2014-10-17 00:29:59

+0

給句子一個非顯式的構造函數,它需要一個單詞來創建一個單詞的句子。現在,您只需要一個非會員操作員+兩個句子,並且您也可以將文字傳遞給它。 – 2014-10-17 00:30:43

+0

@MattMcNabb:這是不正確的。只要聲明瞭Sentence,就可以聲明返回'Sentence'的函數。除非您還定義了函數,否則不需要定義'Sentence'。 – 2014-10-17 00:34:36

回答

4

在C++的話,運營商根本不必成爲會員。所以只要定義操作你的類之外:

Sentence operator+(const Word &word, const Sentence &sentence); 

另外請注意,您可以轉發聲明類:

class Sentence; // forward declaration 

class Word { 
    Sentence operator+(const Sentence &sentence) const; 
}; 

class Sentence { 
    ... 
}; 

// Now that Sentence is defined (not just declared), 
// you can define operator+ for Word (instead of just declaring it) 
Sentence Word::operator+(const Sentence &sentence) const { 
    ... 
} 
+0

整個運營商+方法將會變得緩慢,複製鏈接列表數百萬次。隨它吧。 – 2014-10-17 00:36:36

+0

@DIetrickEpp好的讓我們刪除所有這些註釋 – 2014-10-17 00:59:27

+0

我應該注意到我的類全部由頭文件和實現文件分開。 所以我嘗試了兩種方法。第一種方式不斷給我一個錯誤,說這個函數已經在其他地方定義了。 另一個給我一個錯誤,說班級的句子是不完整的。我一直在試圖解決那裏幾個小時的錯誤。 – user3400223 2014-10-19 00:41:00