简体   繁体   English

C ++中的逗号运算符

[英]comma operator in c++

Below is the code. 下面是代码。

#include<iostream>

using namespace std;

class x {
    int a;
public :
    x(int t=2):a(t) {}
    void print (){
        cout <<"value is "<<a;
    }
    x& operator,(x&a){
        return *this;
    }
};

int main(){
    x a(1),b(2),c(3),d(4);
    x t=(a,b,c,d);
    t.print();
    return 0;
}

output value is 1 输出 value is 1
please explain why the value is not 4 in this line xt=(a,b,c,d); 请解释为什么在此行xt =(a,b,c,d)中的值不是4;

x t = (a,b,c,d);

No matter what order this expression is evaluated in, the left-most operand will always be returned because this in your x& operator , (x &instance) refers to the left operand while instance refers to the right. 无论什么样的顺序该表达式计算中,最左边的操作数总是被退回,因为this在你的x& operator , (x &instance)是指左边的操作数,而instance指的是正确的。

It is thus returning a and you are getting a printed value of 1 . 因此,它返回a并且您得到的打印值为1

If you didn't overload the comma operator, you may get 4 because an expression like (a, b, c) will return the right-most operand. 如果不重载逗号运算符,则可能会得到4因为类似(a, b, c)的表达式将返回最右边的操作数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM