Reputation: 1965
I would like to create a class similar to std::cout. I know how to overload the >> and << operators, but I would like to overload the << operator so it would be input, just like in std::cout.
it should be somthing like:
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)";
Thanks
Upvotes: 1
Views: 390
Reputation: 1965
I think the most general answer would be:
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 was pasted from Timbo's answer here
Thanks for the answers!
Upvotes: 0
Reputation: 258618
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;
}
};
Upvotes: 4