私が取り組んでいるプロジェクトでは、Score
以下で定義されているクラスがありますscore.h
。私はそれをオーバーロードしようとしているので、<<
操作が実行される_points + " " + _name
と出力されます。
これが私がやろうとしたことです:
ostream & Score::operator<< (ostream & os, Score right)
{
os << right.getPoints() << " " << right.scoreGetName();
return os;
}
返されるエラーは次のとおりです。
score.h(30) : error C2804: binary 'operator <<' has too many parameters
(このエラーは実際には 4 回表示されます)
オーバーロードをフレンド関数として宣言することで、なんとか機能させることができました。
friend ostream & operator<< (ostream & os, Score right);
またScore::
、score.cpp の関数宣言から を削除します (事実上、メンバーとして宣言しません)。
なぜこれは機能するのに、前のコードは機能しないのですか?
御時間ありがとうございます!
編集
ヘッダーファイルのオーバーロードへの言及をすべて削除しました...それでも、次の(そして唯一の)エラーが発生します。binary '<<' : no operator found which takes a right-hand operand of type 'Score' (or there is no acceptable conversion)
main() のテストで適切なオーバーロードが見つからないのはなぜですか? (それは含まれていません、私はチェックしました)
以下はフルスコアです.h
#ifndef SCORE_H_
#define SCORE_H_
#include <string>
#include <iostream>
#include <iostream>
using std::string;
using std::ostream;
class Score
{
public:
Score(string name);
Score();
virtual ~Score();
void addPoints(int n);
string scoreGetName() const;
int getPoints() const;
void scoreSetName(string name);
bool operator>(const Score right) const;
private:
string _name;
int _points;
};
#endif