[英]Overloading ostream operator<< works for std::cout, but not for boost::log
[英]overloading operator >> like std::cout
我想创建一个类似于std :: cout的类。 我知道如何重载>>和<<运算符,但我想重载<<运算符,因此它将被输入 ,就像在std :: cout中一样。
它应该是这样的:
class MyClass
{
std::string mybuff;
public:
//friend std::???? operator<<(????????, MyClass& myclass)
{
}
}
.
.
.
MyClass class;
class << "this should be stored in my class" << "concatenated with this" << 2 << "(too)";
谢谢
class MyClass
{
std::string mybuff;
public:
//replace Whatever with what you need
MyClass& operator << (const Whatever& whatever)
{
//logic
return *this;
}
//example:
MyClass& operator << (const char* whatever)
{
//logic
return *this;
}
MyClass& operator << (int whatever)
{
//logic
return *this;
}
};
我认为最常见的答案是:
class MyClass
{
std::string mybuff;
public:
template<class Any>
MyClass& operator<<(const Any& s)
{
std::stringstream strm;
strm << s;
mybuff += strm.str();
}
MyClass& operator<<( std::ostream&(*f)(std::ostream&) )
{
if( f == std::endl )
{
mybuff +='\n';
}
return *this;
}
}
std :: endl在这里粘贴了Timbo的答案
谢谢你的回答!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.