Kam*_*mek 3 c++ comparison negation
让我们拿一些代码示例:
! 4 > 0;
Run Code Online (Sandbox Code Playgroud)
从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;
}
Run Code Online (Sandbox Code Playgroud)
该计划的输出将是:
t > 0;
operator>
! t > 0;
operator!
!t.operator>(0)
operator>
Run Code Online (Sandbox Code Playgroud)
这里提出了我的问题.为什么SomeObjInstance > 0电话不同于SomeObjInstance.operator>(0).我知道以第二种方式(作为成员)呼叫运营商并不常见,但为什么这种呼叫有所不同?如果成员操作员不存在,我总是认为这SomeObjInstance > 0是在成员调用SomeObjInstance.operator>(0)或函数调用下翻译的bool operator>(const Test &, int).
在C++标准中描述了这种行为,或者这可能是某种未定义的行为?
成员访问运算符.*的优先级高于否定运算符!.
在C++标准中描述了这种行为,或者这可能是某种未定义的行为?
这很可能是相关段落:
13.5重载运算符[over.oper]
5)通常不直接调用运算符函数; 相反,它们被调用来评估它们实现的运算符(13.5.1 - 13.5.7).但是,可以使用operator-function-id作为函数调用语法(5.2.2)中函数的名称来显式调用它们.
在您的第一个示例中t > 0;,它将使用具有关系比较运算符优先级的相应运算符.但是,在第二个版本中,t.operator>(0)您将其用作函数调用.因此,Test::operator>它被用作成员函数,这将导致您描述的行为,因为它失去了它的运算符特性("它们可以被显式调用,但是,使用operator-function-id作为函数调用中函数的名称语法").
也可以看看: