【问题标题】:Operator Overloading C++ - Overloading the output "<<" operator运算符重载 C++ - 重载输出“<<”运算符
【发布时间】:2011-12-05 21:00:02
【问题描述】:

我刚刚开始学习基本的 C++ 语法,我对遇到的一段代码有点困惑。

对于创建的名为 MyString 的类,有一个运算符重载定义为:

ostream& operator<<(ostream& os, const MyString& s)
{
    os << s.data;
    return os;
}

然后在一些驱动函数中声明:

cout << s3 << endl;

已运行,其中 s3 是对象类型 MyString。结果打印出 s3 的值。

我不太明白这个语句的作用。在弄乱它之后,似乎调用了一次复制构造函数,然后解构了 3 个对象。这条线究竟是如何工作的?似乎操作员接受对 ostream 和 MyString 的引用,但 endl 也不是吗?另外,当使用了两个“

【问题讨论】:

  • 你在学习哪本书?
  • 这个太笼统了,这里没法回答,你需要参考一本好书。
  • C++ Primer 第 4 版,作者 Lippman
  • 你称之为基本的 c++ 语法?另外,刚开始学习 c++ 时重载运算符 :) ?
  • 如果您希望我们说明MyString 实例有多少个副本,您需要提供更完整的代码示例。如果没有完整的示例,我们无法诊断此问题。

标签: c++ operator-overloading


【解决方案1】:

这是一个非常笼统的问题,但我会尽力消除您的误解。

当您说ostream&amp; operator&lt;&lt;(ostream&amp; os, const MyString&amp; s) { ... } 时,您只是定义了一个函数,该函数将ostream&amp; 作为第一个参数,将const Mystring&amp; 作为第二个参数,并返回一个ostream&amp;。该函数恰好名为operator&lt;&lt;,可以通过简写语法x &lt;&lt; y调用operator&lt;&lt;(x, y)

当你做cout &lt;&lt; s3 &lt;&lt; endl;时,它和做operator&lt;&lt;(operator&lt;&lt;(cout, s3), endl);是一样的。

此代码中没有调用MyString 的复制构造函数和析构函数。您看到的消息来自其他地方。

【讨论】:

    【解决方案2】:

    你可以分解一下:

    cout // this is the ostream your inserting to (stdout)
      << s3 // this calls your defined operator that writes s.data
      << endl; // this calls the operator<< for std::endl
    
    ostream& operator<<(ostream& os, const MyString& s)
    {
        // here os is the ostream (stdout) you're using via cout
        // s is s3 that you passed in
        os << s.data; // this calls operator<< for data
        return os; // this returns the reference so the subsequent call to << endl can append to the stream
    }
    

    【讨论】:

      【解决方案3】:

      调用此语句不需要 MyString 复制构造函数,因为 MyString 是作为对自定义运算符的引用传递的

      endl 发送给自定义操作符

      【讨论】:

      • 所以 s3
      • 没有s3
      【解决方案4】:

      我猜你的编译器可以为 cout 生成复制构造函数。流是一个相当复杂的对象,但 C++ 的选择是提供这样的语法糖(如内联构造函数)来抽象一些细节。其他答案已经指出了使用引用不复制参数传递的要点。

      【讨论】:

        【解决方案5】:

        语言规则说,如果在与 MyString 相同的命名空间中定义了一个非成员函数(运算符

        【讨论】:

        • 当我从 MSVC2003 切换到 MSVC2005 时,我直接体验到了这种行为:我有类似 ofstream("log")
        猜你喜欢
        • 1970-01-01
        • 2021-07-01
        • 2016-02-19
        • 1970-01-01
        • 1970-01-01
        • 2013-12-15
        • 2012-12-30
        • 2012-11-26
        相关资源
        最近更新 更多