2010-05-13 48 views
1

我編輯了這個問題的一篇文章,但沒有得到答案。讓編譯器感知<<爲特定類定義

我超負荷< <爲一類,Score(在score.h中定義),在score.cpp中。

ostream& operator<< (ostream & os, const Score & right) 
{ 
os << right.getPoints() << " " << right.scoreGetName(); 
return os; 
} 

getPoints獲取的int屬性,getName一個string一個)

我得到了在main()的測試,包含在main.cpp中這個編譯錯誤

binary '<<' : no operator found which takes a right-hand operand of type 'Score' (or there is no acceptable conversion) 

怎麼來的編譯器不會'認識到'重載是有效的? (包括正確)

感謝您的時間。

編輯:

按照要求,代碼導致錯誤:

cout << ":::::\n" << jogador.getScore() << endl; 

jogadorPlayer對象,其中包含一個Score之一。 getScore返回該屬性。

+1

你一定要發佈導致錯誤的代碼 – UncleZeiv 2010-05-13 17:12:45

回答

4

也許你沒有聲明你的operator<<score.h?它通常應該包含這樣的:

ostream& operator<< (ostream & os, const Score & right); 

編輯:更準確的說,應該是:

std::ostream &operator<<(std::ostream &os, const Score &right); 

你一定要在頭一個using namespace std;,所以你需要std::它正常工作。

+0

這是行不通的,因爲左側參數不是「Score」類型。至少,這裏的另一個問題讓我想到了。 – 2010-05-13 17:17:56

+0

@Francisco P. - 編譯器抱怨左值,而不是左值。即,它擔心右手參數。 – 2010-05-13 17:23:45

+2

不要把這一行放在類聲明中,在類聲明後放*。 – 2010-05-13 17:25:34

2

嘗試宣告operator<<朋友功能類:

struct Score 
{ 
    friend ostream& operator<<(ostream& output, const Score& right); 
}; 

這將使你的Score結構很好地適應報表打印:

Score my_score; 
cout << my_score << endl; 

如有疑問,請檢查C++ FAQ

+0

我正在尋找不同的方式來做到這一點。即使它有效,我也沒有理由需要朋友操作員<<。我更喜歡接受的答案的建議。但是感謝您的時間/精力幫助我。 – 2010-05-13 17:33:01

+1

如果Score :: getPoints()和/或Score :: scoreGetName()是私人的,這個答案很有用。但是我不認爲你需要接口原理的結構分數。 – 2010-05-13 17:40:20

相關問題