2016-04-06 18 views
0

このコードはエラーを分析するのに十分だと思います。演算子<<オーバーロード中エラー>>「const ....」を渡す

私は私のコードをコンパイルするとき、私は次のエラーを取得:

error: passing ‘const EventClass’ as ‘this’ argument of ‘std::string EventClass::getEventName()’ discards qualifiers [-fpermissive]
outStream << eventObject.getEventName() << " event at "

error: passing ‘const EventClass’ as ‘this’ argument of ‘int EventClass::getEventTime()’ discards qualifiers [-fpermissive]
<< eventObject.getEventTime() << endl;

error: invalid initialization of reference of type ‘std::ofstream& {aka std::basic_ofstream&}’ from expression of type ‘std::ostream {aka std::basic_ostream}’
return(outStream);

任意のアイデアをどのようにこれらのエラーを解決するには?そのgetEventName()getEventTime()方法は例えば、彼らは彼らが上と呼ばれているオブジェクトを変更しないことを指定するには、constと同様に宣言する必要があるので、

+1

'getEventName'メソッドは' const'とマークされていますか? –

+0

いいえ、そうではありません。それは問題を解決するためにconstでなければなりませんか? – nm17

+0

はい、問題を解決するにはconstでなければなりません。 – kfsone

答えて

0

eventObjectは、constオブジェクトへの参照です:

std::string getEventName() const; 
int getEventName() const; 

また、あなたのオペレータはofstreamを返すよう宣言されているが、それは入力と一致するように、代わりにostreamを返す必要がある:

ostream& operator<<(ostream &outStream, const EventClass &eventObject) 
3

あなたはトンを必要とします次のようにO getEventNamegetEventTimeを確認するには、constとして宣言されています

std::string getEventName() const; 
int getEventTime() const; 

EventClassの宣言と実装に。これは、これらのメソッドがオブジェクトのフィールドを変更しないことをコンパイラに指示します。

また、オペレータの最後の行は、単純にする必要があります:return outStream;

編集:またstd::ofstreamstd::ostreamと同じではありません。任意のストリームタイプを包含する

std::ostream& operator<<(std::ostream& os, const EventClass& eventObject) { 
    //blah 
} 

:一般的に、operator<<のために、それは以下のように定義する必要があります。

+1

最後のエラーでは、 'ostream'と' ofstream'が同じではないことも指摘しておきましょう。 –

関連する問題