2011-01-17 14 views
1

fstreamを使用していてエラーが発生しました。iostreamでC++コンパイルエラーが発生しました

class CLog 
{ 
    void printOn(std::ostream& dbg) const; 
} 

void operator>>(const CLog& s, std::ofstream& dbg) 
{ 
    s.printOn(dbg); 
} 

しかし、私はコンパイル時に、私は次のエラーました:ofstreamのは、それが不可能なので、なぜostreamに継承することを

error C2664: 'printOn' : cannot convert parameter 1 from 
'class std::basic_ofstream<char,struct std::char_traits<char> >' to 
'class std::basic_ostream<char,struct std::char_traits<char> > &' 
A reference that is not to 'const' cannot be bound to a non-lvalue 

私は思ったがここ

は私が持っているものでしょうか?出力オペレータの

おかげ

+0

Arggg!見つからなかった '#include 'を見つけました。コンパイラからの愚かな出力。ありがとうございます – mathk

答えて

2

はprintOn公開を行い、fstreamのヘッダを:)含みます。

#include <fstream> 
class CLog 
{ 
public: 
    void printOn(std::ostream& dbg) const 
    { 

    } 
}; 

std::ofstream & operator<<(std::ofstream& dbg, const CLog& s) 
{ 
    s.printOn(dbg); 
} 
+0

printOnが公開されていましたfstreamがありがたいです:)しかし、このような状況でコンパイラの出力が役に立たないのはなぜですか? – mathk

+0

ええ、それは私を混乱させました:) – UmmaGumma

+0

また、演算子>>のパラメータの順序を入れ替えることに注目する価値があります。ストリームが左側にある抽出演算子にとって重要です。あなたが実際に演算子<<であることを意味していた場合、別の答えが指摘しているように、パラメータの順序は正しいです – lefticus

6

より正確な宣言は以下の通りである:

std::ostream& operator << (std::ostream& dbg, const CLog& s) 
{ 
    s.printOn(dbg); 
    return dbg; 
} 
+0

は演算子でなければなりません>> – Ferruccio

+0

そして、あなたはCLogクラスのフレンド操作として宣言することができます。 –

+1

これはうまくいきませんでした。 – mathk

1

私は、問題を再現することができ完全コードを掲示することをお勧めしたいです。私は誰も持っていません:

#include <fstream> 

class CLog 
{ 
public: 
    void printOn(std::ostream& dbg) const; 
}; 

void operator>>(const CLog& s, std::ofstream& dbg) 
{ 
    s.printOn(dbg); 
} 
関連する問題