将对象格式化为字符串

Hah*_*ess 2 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";
    }
}
Run Code Online (Sandbox Code Playgroud)

是否有类似的东西可以让我将一个对象流入cout?

cout << Test() << endl;
Run Code Online (Sandbox Code Playgroud)

Bil*_*ill 5

相当于过载operator<<:

#include <ostream>

class Test
{
  int t;
};

std::ostream& operator<<(std::ostream& os, const Test& t)
{
   os << "Hello";
   return os;
}
Run Code Online (Sandbox Code Playgroud)

然后你会像这样使用它:

#include <iostream>

int main()
{
  std::cout << Test() << " There" << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

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

  • *重载*,而不是覆盖(覆盖意味着`ostream`和`Test`的`operator <<`已经存在并且你正在覆盖它). (2认同)
  • template <typename Char,typename Traits> std :: basic_ostream <Char,Traits>&operator <<(std :: basic_ostream <Char,Traits>&os,const Test&t)适用于所有类型的输出流,包括std: :例如wcout,相当于为wchar_t类型指定的std :: cout. (2认同)