c++ - 将对象格式化为字符串

标签 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;

最佳答案

相当于重载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

关于c++ - 将对象格式化为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7457959/

相关文章:

python - 如何只替换字符串中的特定点?

format - 在格式模块上配置更大的列数限制

php - 文档中 PHP + Ajax 之间加载数据时的最佳实践

go - Linux 和 macOS 上 Go 中 RFC3339 时间格式化结果不同

c++ - 如何在此代码中仅显示素数?

c++ - 更改一个对象的引用并且它会更改集合中的所有对象

c# - 支持混合空格和制表符的编辑器?

C++17 std::from_chars 和 std::to_chars 的用途?

.net - 由于 2 秒超时,并非所有 native 全局变量都在混合模式 .Net 应用程序中被破坏

java - 如何制作不重叠的用户名和密码测试方法?