【问题标题】:Error while overloading <<. What am I doing wrong here?重载 << 时出错。我在这里做错了什么?
【发布时间】:2015-11-30 05:56:22
【问题描述】:

我正在学习 C++,我正在研究重载 No match for operator”。我在这里做错了什么?以下是我的代码:

#include <iostream>

using namespace std;

class Time
{
private:
    int hour;
    int minute;
    int second;

public:
    Time(int hh, int mm, int ss)
    {
        second = ss%60;
        mm +=ss/60;

        minute = mm%60;
        hh +=mm/60;

        hour = hh;
    }

    ostream& operator<<(ostream &out);  //overloading << function declaration
};

ostream& Time::operator <<(ostream &out) // overloading << function definition
{
    out << "Time - " << hour << ":" << minute << ":" << second;

    return out;
}

int main()
{
    using namespace std;

    Time tm(10,36,60);
    cout << tm;

    return 0;
}

【问题讨论】:

    标签: c++ function class io operator-overloading


    【解决方案1】:

    功能

    ostream& operator<<(ostream &out);
    

    定义&lt;&lt;,使得LHS 是Time 对象,RHS 是std::ostream 对象。

    它可以用作:

    Time tm(10,36,60);
    tm << cout;
    

    不像

    cout << tm;
    

    使用

    cout << tm;
    

    您需要定义一个 LHS 类型为 std::ostream 的函数。因此,它不能是Time 的成员函数。

    将函数声明为:

    friend ostream& operator<<(ostream &out, Time const& ti);
    

    并相应地实施。

    【讨论】:

      【解决方案2】:

      当您有成员运算符重载时,运算符的左侧是该类的对象。所以你的会员:

      ostream& operator<<(ostream &out); 
      

      实际上会匹配用法:

      tm << cout
      

      但不是cout &lt;&lt; tm

      要解决此问题,您应该使用非成员函数。我的首选方式是:

      // not inside a class definition
      ostream &operator<<(ostream &os, Time const &tm)
      {
          // output using public methods of tm
      
          return os;
      }
      

      然而,另一种常见的技术是使用友元函数:

      // Inside Time's class definition
      friend ostream &operator<<(ostream &os, Time const &tm)
      {
          // output using private members of tm
      
          return os;
      }
      

      请注意,即使后者出现在类定义中,它实际上也不是成员函数。 friend 关键字就是如此。

      【讨论】:

      • 哦...哎呀。我没看到。无论如何都赞成;)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-03-03
      • 2013-06-28
      • 2023-01-19
      • 1970-01-01
      • 1970-01-01
      • 2017-06-07
      • 1970-01-01
      相关资源
      最近更新 更多