【发布时间】:2012-11-13 12:19:11
【问题描述】:
让我们来一些代码示例:
! 4 > 0;
根据 C++ 标准,我们知道,首先进行否定,而不是比较。但如果我们稍微扩展一下这个例子:
#include <iostream>
class Test
{
public:
bool operator!() const
{
std::cout << "operator!" << std::endl;
return false;
}
bool operator>(const int &) const
{
std::cout << "operator>" << std::endl;
return false;
}
};
int main(int argc, char * argv[])
{
Test t;
std::cout << "t > 0;" << std::endl;
t > 0;
std::cout << "! t > 0;" << std::endl;
! t > 0;
std::cout << "!t.operator>(0)" << std::endl;
! t.operator>(0);
return 0;
}
这个程序的输出将是:
t > 0;
operator>
! t > 0;
operator!
!t.operator>(0)
operator>
- 第一次调用(控制调用)很清楚。我们检查是否调用了我们想要的运算符。
- 第二次调用是我第一次陈述的证明。首先调用否定运算符,然后调用结果(布尔)运算符>。
- 第三个电话让我很困扰。
这里提出了我的问题。为什么SomeObjInstance > 0 调用与SomeObjInstance.operator>(0) 不同。我知道以第二种方式(作为成员)调用操作员并不常见,但为什么这种调用不同?我总是认为SomeObjInstance > 0 被翻译成成员调用SomeObjInstance.operator>(0) 或函数调用bool operator>(const Test &, int) 如果成员运算符不存在。
这种行为在 C++ 标准中的描述,或者这可能是某种未定义的行为?
【问题讨论】:
标签: c++ comparison negation