<<
オブジェクトをストリームにリダイレクトするには、演算子をオーバーロードする必要があります。
メンバー関数としてオーバーロードできますが、この場合、object << stream
そのオーバーロードされた関数を使用するには構文を使用する必要があります。
この構文を使用する場合はstream << object
、演算子を「フリー」関数としてオーバーロードする必要があり<<
ます。つまり、NamedStorm クラスのメンバーではありません。
これが実際の例です:
#include <string>
#include <iostream>
class NamedStorm
{
public:
NamedStorm(std::string name)
{
this->name = name;
}
std::ostream& operator<< (std::ostream& out) const
{
// note the stream << object syntax here
return out << name;
}
private:
std::string name;
};
std::ostream& operator<< (std::ostream& out, const NamedStorm& ns)
{
// note the (backwards feeling) object << stream syntax here
return ns << out;
}
int main(void)
{
NamedStorm ns("storm Alpha");
// redirect the object to the stream using expected/natural syntax
std::cout << ns << std::endl;
// you can also redirect using the << method of NamedStorm directly
ns << std::cout << std::endl;
return 0;
}
フリー リダイレクト オーバーロードから呼び出される関数は、NamedStorm のパブリック メソッドである必要があります (この場合operator<<
、NamedStorm クラスのメソッドを呼び出しています)。または、friend
プライベート フィールドにアクセスするには、リダイレクト オーバーロードが NamedStorm クラスの である必要があります。