c++ - a+b 和 operator+(a,b) 的区别

标签 c++ operator-overloading language-lawyer

考虑以下程序:

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

相关文章:

oop - R : Use a different base field/corpus 中的运算符重载和类定义

c++ - 添加这些字符串有什么区别?

c - 从指向 const 的指针中删除 const 是否遵循 C 中的严格别名,并引用同一个对象?

c++ - 依赖基类中的常量使外部定义不匹配?

c++ - 只要您不直接访问它包含的值,它是否通过 memcpy 序列化对象表示而不创建安全的对象?

c++ - 如何在设计实现层面避免内存泄漏

c++ - (重新)使用空间索引库加载 R 树

c++ - 直接减去两个 vector<point2f>

c++ - 在 v8 中将字符串转换为函数

matlab - 访问具有重载索引引用的类的方法和属性