开发者

C++ overloading << operator

I need to overload the << operator for streams to work with built-in types. For strings it's not a problem, since I simply overload the function like this:

ostream& operator<<(ostream& os, const char* str) { /*...*/ }

This works because this function is global, not a member. The problem is that I 开发者_如何学Pythonneed to overload the << operator for other primitive types (ints, floats, etc) but those are member functions. Is there a way I can do this? I need it to work with not only cout but other streams as well. Thanks in advance.


You shouldn't try to change what the operator in std::cout << 3; does. It's part of a standard API. If you need to output in some format which stream manipulators can't support, then for example you could write a little wrapper:

struct MyFormatter {
    MyFormatter (ostream &o) : o(o) {}
    ostream &o;
};

MyFormatter &operator<<(MyFormatter &mf, int i) {
    mf.o << "int(" << i << ")"; // or whatever
    return mf;
}

Then use it like this:

MyFormatter mf(std::cout);
mf << 1 << "," << 2 << "," << 3;


In C++, operator overloads require at least one operand of a "class type" or enumeration type.
The point is you are not allowed to overload operator for primitive types.
http://www.parashift.com/c++-faq-lite/intrinsic-types.html#faq-26.10

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜