【问题标题】:Using my own String class with the << operator将我自己的 String 类与 << 运算符一起使用
【发布时间】:2016-09-12 23:10:33
【问题描述】:

我正在寻找一种将 ostream 与我的自定义字符串类一起使用的方法,并重载运算符

我对 iostream 的内部工作方式相当陌生,但据我了解,我所看到的将 std::stringbuf 作为我的自定义 stringstream 的基础的方法不起作用,因为 stringbuf 处理 std::string。

本质上我希望能够做到这一点(或类似的):

MyStringClass string
MyOutput << "hello" << string << "World" << std::endl;

可以将 MyOutput 更改为打印到我想要​​的任何位置。

谢谢。

【问题讨论】:

    标签: c++ string operator-overloading ostream


    【解决方案1】:

    没问题。定义你的类,并在它的定义中添加一个ostream&amp; operator&lt;&lt;(const String&amp;);

    在该运算符中,您可以编写任何您想要的处理代码(查看 std::string 以获得灵感)

    【讨论】:

    • 就这么简单吗?但是我的字符串输出到的 ostream 不处理 std::strings 吗?还是我只是忽略了这一点,并在运算符定义中进行“打印”?谢谢
    • ostreamcout 的类型;它与 std::string 无关。我的声明将允许您使用cout &lt;&lt; yourstring,但您不必使用 cout;使用您想要的任何目的地。
    • @LukeBourne 在您的&lt;&lt; 函数中,您必须输出一些已经定义了输出方法的其他类型,例如std::string
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-06
    • 2020-04-22
    • 2017-11-17
    • 2013-09-10
    相关资源
    最近更新 更多