将对象格式化为字符串

时间:2011-09-17 21:34:15

标签: c++ string format

我在使用Java很长一段时间后回到了c ++。在Java中,覆盖对象上的toString方法允许将对象自动转换为字符串并连接到其他字符串。

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

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

是否有类似的内容可以让我将对象流式传输到cout中?

cout << Test() << endl;

2 个答案:

答案 0 :(得分:5)

等效于重载operator<<

#include <ostream>

class Test
{
  int t;
};

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

然后你会像这样使用它:

#include <iostream>

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

请参阅操作代码:http://codepad.org/pH1CVYPR

答案 1 :(得分:2)

常见的习惯用法是创建一个operator<<的重载,它将输出流作为左侧操作数。

#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;
}

如果您想支持包含其他字符类型(例如wchar_t)/模板参数的流,您必须为要支持的各种类型的流写入不同的重载,或者,如果您的代码是(或多或少)独立于这些类型,您只需编写模板operator<<

相关问题