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

标签 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?

感谢任何帮助。

最佳答案

Why control is not reaching comma operator for ob1?

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

这行代码相当于

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

清楚地表明它只被调用了两次。 ob1 被求值,但运算符不对其执行任何操作。

关于c++ - 无法理解逗号运算符的工作原理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18872304/

相关文章:

c++ - AfxPumpMessage() 用于什么?

c++ - 在 C++ 中不允许变量的默认值是非静态方法或类成员的原因是什么?

c++ - 从 Lua 设置 C 属性

c++ - count[x]++ 在 map 上的安全性如何

c++ - DebugView 打印列显示 "????"

c++ - 将数字从字符串流转换为具有设定精度的字符串

c++ - wxwidget2.9.2在linux下的使用方法

C++ vector 异常处理 : Which one is the better way of throwing out_of_range() and why?

c++ - 如何构建高效的命名数组?

c++ - 关于 DSO 引用隐藏符号的警告到底意味着什么?