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;但不会调用成员运算符函数。

海合会喊道:

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++ 的细微差别。

4

1 回答 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是 a const comma_op&,那么方法一定是const方法。但是您只提供了一个非const operator,,因此将使用默认定义。

于 2010-02-25T15:16:57.913 回答