C++: 运算符,(逗号)似乎不起作用
我现在正在编写我的课程并对其进行测试。看来逗号运算符(operator,)拒绝工作,程序只是跳过它。这是我正在运行的代码,
fileObj << buffer,40;
我编写了以下运算符(仅显示原型,代码不相关):
const file_t& operator<<(const void* buffer);
void operator,(int length);
“operator<<”工作正常,程序使用它,但是当它到达“操作员”时,它只是跳过它,就像它根本不存在一样。不用说,两个运营商相互依赖。
知道为什么跳过逗号运算符吗?谢谢。
I'm writing my class now and testing it. It seems that the comma operator (operator,) refuses to work, the program simply skips it. This is the code I'm running
fileObj << buffer,40;
I wrote the following operators (only prototypes shown, the code isn't relevant):
const file_t& operator<<(const void* buffer);
void operator,(int length);
the "operator<<" works fine, the program uses it but when it arrives to the "operator," , it simply skips it like it doesn't even exist. Needless to say that both operators depend on each other.
Any idea why the comma operator is being skipped? Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的
<<
运算符返回一个 const file_t 引用。您的逗号运算符是一个非常量函数。由于类型不匹配,编译器不会选择逗号运算符来执行操作。相反,它使用内置的逗号运算符,该运算符仅计算两个操作数并返回正确的操作数。 (并且由于在您的示例中对正确操作数的求值没有副作用,因此看起来好像根本没有调用它。)如果您的逗号运算符没有修改它所调用的对象,则将其设为常量:
如果运算符需要要修改您的对象,则不要从
<<
运算符返回 const 对象:Your
<<
operator returns a const file_t reference. Your comma operator is a non-const function. Since the types don't match, the compiler does not select your comma operator to perform the operation. Instead, it uses the built-in comma operator, which simply evaluates both operands and returns the right one. (And since evaluation of the right operand has no side effects in your example, it appears as though it's not called at all.)If your comma operator doesn't modify the object it's called on, then make it const:
If the operator needs to modify your object, then don't return a const object from your
<<
operator: