简体   繁体   English

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

[英]Difference between a+b and operator+(a,b)

Consider the following program: 考虑以下程序:

#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
}

Why does the last line f+f; 为什么最后一行f+f; not compile? 无法编译? Why is it not identical to operator+(f,f); 为什么它与operator+(f,f); ? A reference to the standard would be appreciated. 对标准的引用将不胜感激。

The type of f is a built-in type. f的类型是内置类型。 Operations on objects of built-in types never consider user-define operators. 内置类型的对象上的操作永远不会考虑用户定义的运算符。 Calling operator+(f, f) explicitly force two conversions which will not happen unless they are forced. 调用operator+(f, f)显式强制执行两次转换,除非将其强制执行,否则不会发生。 The relevant clause is 13.3.1.2 [over.match.oper] paragraph 1: 相关条款是13.3.1.2 [over.match.oper]第1段:

If no operand of an operator in an expression has a type that is a class or an enumeration, the operator is assumed to be a built-in operator and interpreted according to Clause 5. ... 如果表达式中没有运算符的操作数具有类或枚举的类型,则假定该运算符是内置运算符,并根据第5章进行解释。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM