我试图用一个非友元非成员函数重载逗号运算符,就像这样:
#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++的细微差别。