重载运算符:第一个参数是对应左操作数还是第二个参数对应右操作数?

时间:2016-05-01 01:20:33

标签: c++ stream operator-overloading

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

我试图重载“<<”运营商像这样使用它:

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;
}

2 个答案:

答案 0 :(得分:3)

是的,这一切都像你说的那样有效。

答案 1 :(得分:2)

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

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

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