无法理解逗号运算符的工作原理

时间:2013-09-18 12:29:07

标签: c++

在下面的程序中,我重载了commaoperator。但是,为什么comma operator没有考虑first element/object

class Point {
  int x, y;
public:
  Point() {}
  Point(int px, int py) 
  {x = px;y = py;}
  void show() {
    cout << x << " ";
    cout << y << "\n";
  }
  Point operator+(Point op2);
  Point operator,(Point op2);
};

// overload comma for Point
Point Point::operator,(Point op2)
{
  Point temp;
  temp.x = op2.x;
  temp.y = op2.y;
  cout << op2.x << " " << op2.y << "\n";
  return temp;
}

// Overload + for Point
Point Point::operator+(Point op2)
{
  Point temp;
  temp.x = op2.x + x;
  temp.y = op2.y + y;
  return temp;
}

int main()
{
  Point ob1(10, 20), ob2( 5, 30), ob3(1, 1);
  Point ob4;
  ob1 = (ob1, ob2+ob2, ob3);//Why control is not reaching comma operator for ob1?
  ob1 = (ob3, ob2+ob2, ob1);//Why control is not reaching comma operator for ob3?
  ob4 = (ob3+ob2, ob1+ob3);//Why control is not reaching comma operator for ob3+ob2?
  system("pause");
  return 0;
}

我也尝试了解,运算符,但无法找到解决方案。

  ob1 = (ob1, ob2+ob2, ob3);//Why control is not reaching comma operator for ob1?
  ob1 = (ob3, ob2+ob2, ob1);//Why control is not reaching comma operator for ob3?
  ob4 = (ob3+ob2, ob1+ob3);//Why control is not reaching comma operator for ob3+ob2?

任何帮助表示感谢。

4 个答案:

答案 0 :(得分:5)

  

为什么控制没有到达ob1的逗号运算符?

我猜你在问,为什么这一行只输出两个点:10 60ob2+ob21 1ob3。这是因为你只调用逗号运算符两次;每次,它输出右手参数并忽略其左手参数。

代码行相当于

ob1.operator,(ob2+ob2).operator,(ob3);

明确表示它只被调用两次。 ob1已被评估,但操作员不对其做任何事情。

答案 1 :(得分:2)

确实达到了它。但是,由于您只打印出operator,this的参数值,因此您无法打印出来。

答案 2 :(得分:2)

ob1 = (ob1, ob2+ob2, ob3);//Why control is not reaching comma operator for ob1?

确实如此,你只是没有注意到它 您将运算符定义为成员函数。现在让我们重写上面的表达式,忽略赋值运算符的左侧:

    (ob1.operator,(ob2+ob2)).operator,(ob3);
 // ^^^^^^^^^^^^^^^^^^
 // displays contents of ob2+ob2
 //                      ^^^^^^^^^^^^^^
 //                   displays contents of ob3

或等效,但更容易理解:

 {
     Point temp = ob1.operator,(ob2+ob2);
     temp.operator,(obj3);
 }

答案 3 :(得分:1)

您永远不应该更改您正在重载的运算符的语义。逗号运算符计算左表达式,执行任何副作用,丢弃结果,然后计算第二个并返回评估结果(和类型)。