开发者

Formatting objects into strings

I'm coming back to c++ after using Java for a long time. In Java overriding the toString method on an object allows the object to be automatically translated into a string and concatenated to other strings.

class Test {
    public static void main(String[] args) {
        System.out.开发者_JAVA技巧println(new Test() + " There"); // prints hello there
    }

    public String toString() {
        return "Hello";
    }
}

Is there anything similar that would allow me to stream an object into cout?

cout << Test() << endl;


The equivalent is to overload operator<<:

#include <ostream>

class Test
{
  int t;
};

std::ostream& operator<<(std::ostream& os, const Test& t)
{
   os << "Hello";
   return os;
}

You would then use it like this:

#include <iostream>

int main()
{
  std::cout << Test() << " There" << std::endl;
}

See the code in action: http://codepad.org/pH1CVYPR


The common idiom is to create an overload of operator<< that takes an output stream as the left-hand operand.

#include <iostream>

struct Point
{
    double x;
    double y;
    Point(double X, double Y)
      : x(X), y(Y)
    {}
};

std::ostream & operator<<(std::ostream & Stream, const Point & Obj)
{
    // Here you can do whatever you want with your stream (Stream)
    // and the object being written into it (Obj)
    // For our point we can just print its coordinates
    Stream<<"{"<<Obj.x<<", "<<Obj.y<<"}";
    return Stream; // return the stream to allow chained writes
}

int main()
{
    Point APoint(10.4, 5.6);
    std::cout<<APoint<<std::endl; // this will print {10.4, 5.6}
    return 0;
}

If you want to support streams with other character types (e.g. wchar_t)/template parameters of the streams you have to write different overloads for the various types of streams you want to support, or, if your code is (more or less) independent from such types, you can simply write a template operator<<.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜