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

6

我试图用一个非友元非成员函数重载逗号运算符,就像这样:

#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;
}

基本上,我正在尝试让逗号运算符与浮点数在两侧都可用。只有拥有成员函数才能让我编写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


注意: 我知道重载运算符,尤其是逗号运算符,会让人感到困惑,从纯粹主义的角度来看,这并不可取。在这里,我只是学习C++的细微差别。


2
作为一种风格,我认为通常被认为重新定义运算符的含义是不明智的,因为这会导致难以维护的代码:a * b是进行乘法运算还是已被重新定义为向量叉积?(有些人可能会说这样做没问题。) - Skizz
@Skizz:我猜你可能没有注意到,我在这篇文章一开始就提到的「注释」。 - legends2k
逗号重载经常会出现问题,特别是由于其低优先级。 - jk.
1个回答

19
void operator,(const float &rhs)
你需要在这里使用 const
void operator,(const float &rhs) const {
    cout << this->val << ", " << rhs << endl;
}
由于原因是因为。
rhs, lhs

将会调用

rhs.operator,(lhs)

因为rhs是一个const comma_op&,所以该方法必须是一个const方法。但是你只提供了一个非constoperator,,所以默认定义将被使用。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接