1

Possible Duplicate:
How to overload cout behaviour in c++

I would like to make cout act different for string. for example it will always add "Hello" before handovered string. So this is basically overloading operator but for String. How to do it?

Example

std::cout<<" Kermit";

Result

Hello Kermit
4

2 回答 2

2

请不要:

struct X
{
   X& operator << (const char* x)
   {
      std::cout << "Hello " << x;
      return *this;
   }
};

//...
X cout;
cout << "Kermit";
于 2013-02-01T16:35:10.540 回答
0

您可以在文字周围使用包装器...

#include <iostream>

struct foo
{
  foo(const char* s) : str(s) {}

  friend
  std::ostream& operator<<(std::ostream& s, foo const& f)
  { return s << "Hello " << f.str; }

  const char* str;
};

int main(void)
{
  std::cout << foo("Kermit") << std::endl;
}
于 2013-02-01T16:40:10.090 回答