考虑以下程序:
#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 段:
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. ...
关于c++ - a+b 和 operator+(a,b) 的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19307578/