为什么我的重载逗号运算符不会被调用?

leg*_*s2k 6 c++ gcc operator-overloading comma-operator

我试图用这样的非朋友非成员函数重载逗号运算符:

#include <iostream>
using std::cout;
using std::endl;

class comma_op
{
    int val;

public:
    void operator,(const float &rhs)
    {
        cout << this->val << ", " << rhs << endl;
    }
};

void operator,(const float &lhs, const comma_op &rhs)
{
    cout << "Reached!\n";      // this gets printed though
    rhs, lhs;                  // reversing this leads to a infinite recursion ;)
}

int main()
{
    comma_op obj;
    12.5f, obj;

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

基本上,我试图让浮点数从两边使用逗号运算符.有一个成员函数只允许我写obj, float_val,而有一个额外的帮助非朋友非成员函数允许我写float_val, obj; 但是不会调用成员操作符函数.

GCC哭泣:

comma.cpp: In function ‘void operator,(const float&, const comma_op&)’:
comma.cpp:19: warning: left-hand operand of comma has no effect
comma.cpp:19: warning: right-hand operand of comma has no effect
Run Code Online (Sandbox Code Playgroud)


注意: 我意识到重载运算符,这也会使逗号超载.令人困惑,从纯粹主义者的角度来看根本不可取.我只是在这里学习C++的细微差别.

ken*_*ytm 19

void operator,(const float &rhs)
Run Code Online (Sandbox Code Playgroud)

你需要一个const.

void operator,(const float &rhs) const {
    cout << this->val << ", " << rhs << endl;
}
Run Code Online (Sandbox Code Playgroud)

原因是因为

rhs, lhs
Run Code Online (Sandbox Code Playgroud)

将会通知

rhs.operator,(lhs)
Run Code Online (Sandbox Code Playgroud)

由于rhs是a const comma_op&,该方法必须是一种const方法.但是您只提供非const operator,,因此将使用默认定义.