我试图用这样的非朋友非成员函数重载逗号运算符:
#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语言的细微差别.
解决方法
原文地址:https://www.jb51.cc/c/117628.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。