【问题标题】:Overloading Operators: Does the 1st parameter correspond to the left operand and the 2nd one to the right operand?重载运算符:第一个参数对应左操作数,第二个参数对应右操作数吗?
【发布时间】:2016-05-01 01:20:33
【问题描述】:

编写非成员函数重载运算符时,第一个参数对应左操作数,第二个参数对应右操作数吗?

我试图重载“

stream << ClassA << ClassB

下面是一个示例,其中FeetInches 是一个具有成员变量feetinches 的类。

这就是这个参数顺序起作用的原因吗:

ostream &operator<<(ostream &strm, const FeetInches &obj)
{
   strm << obj.feet << " feet, " << obj.inches << " inches";
   return strm;
}

--

但是这个参数顺序不起作用?

ostream &operator<<(const FeetInches &obj, ostream &strm)
{
   strm << obj.feet << " feet, " << obj.inches << " inches";
   return strm;
}

【问题讨论】:

    标签: c++ stream operator-overloading


    【解决方案1】:

    是的,一切都如你所说。

    【讨论】:

      【解决方案2】:

      ostream 排在第一位,因为我们这里没有任何调用对象。

      ostream &operator<<(ostream &strm, const FeetInches &obj)
      {
         strm << obj.feet << " feet, " << obj.inches << " inches";
         return strm;
      }
      

      因为cout&lt;&lt;obj&lt;&lt;endl; 将被解释为operator&lt;&lt;(cout,obj);

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-09-11
        • 2016-04-13
        • 2010-12-13
        • 2020-09-24
        • 1970-01-01
        • 1970-01-01
        • 2018-02-11
        相关资源
        最近更新 更多