5

在下面的程序中,我重载了逗号运算符。但是,为什么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

4 回答 4

5

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

我猜你在问,为什么这条线只输出两点:10 60forob2+ob21 1for ob3。这是因为您只调用了两次逗号运算符;每次,它输出它的右手参数并忽略它的左手参数。

这行代码相当于

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

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

于 2013-09-18T12:39:19.857 回答
2

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

于 2013-09-18T12:37:47.143 回答
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);
 }
于 2013-09-18T12:38:27.260 回答
1

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

于 2013-09-18T12:45:59.187 回答