6

I'm trying to overload the comma operator with a non-friend non-member function like this:

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

Basically, I'm trying to get the comma operator usable from both sides, with a float. Having a member function only allows me to write obj, float_val, while having an additional helper non-friend non-member function allows me to write float_val, obj; but the member operator function doesn't get called.

GCC cries:

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


Note: I realise that overloading operators, that too to overload comma op., Is confusing and is not at all advisable from a purist's viewpoint. I'm just learning C++ nuances here.

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は であるためconst comma_op&、メソッドはメソッドでなければなりませんconst。ただし、 non- のみを指定するconst operator,ため、デフォルトの定義が使用されます。

于 2010-02-25T15:16:57.913 に答える