a+b 和运算符 +(a,b) 之间的区别

Difference between a+b and operator+(a,b)

本文关键字:之间 区别 运算符 a+b      更新时间:2023-10-16

请考虑以下程序:

#include<functional>
typedef std::function< int( int ) > F;
F operator+( F, F )
{
    return F();
}
int f( int x ) { return x; }
int main()
{
    operator+(f,f); // ok
    f+f; // error: invalid operands to binary expression
}

为什么最后一行f+f;不编译?为什么它与operator+(f,f);不同?如能提及该标准,将不胜感激。

f的类型是内置类型。对内置类型的对象的操作从不考虑用户定义运算符。调用operator+(f, f)显式强制进行两次转换,除非强制进行转换,否则不会发生。相关条款是 13.3.1.2 [over.match.oper] 第 1 段:

如果表达式中运算符的操作数没有类型是类或枚举,则假定运算符是内置运算符,并根据条款 5 进行解释。