首页 > 解决方案 > C++中不同数据类型的运算符重载

问题描述

以此为例:

float operator+(int a, float b)
{
   Return b + (float)a;
}

void main()
{
    int a = 10;
    float b = 2.5f;
    float c;

    c = a + b; //works as intended
    c = b + a; //results in type mismatch error
}

所以我的问题是:有没有办法在不定义第二个函数的情况下让参数被双向接受?

标签: c++operator-overloading

解决方案


It is not possible to overload operators for fundamental types. You should only overload operators for classes that you have defined.

A solution for overloading a binary operator for your own class with heterogeneous arguments symmetrically, is to define the operator for first type, and make the second type implicitly convertible to the first.


推荐阅读