能否重载基本数据类型的运算符? RRS feed

  • 问题

  • 为了判断两个浮点数是否相等(误差小于指定值),我在全局空间写了个重载函数:

    bool operator==(const double &a, const double &b)
     return fabs(a-b)<ACCURACY;


    C2803: 'operator ==' must have at least one formal parameter of class type 


    2010年3月22日 7:12


  • The following rules constrain how overloaded operators are implemented. However, they do not apply to the new and delete operators, which are covered separately.

    You cannot define new operators, such as **.

    You cannot redefine the meaning of operators when applied to built-in data types.

    Overloaded operators must either be a nonstatic class member function or a global function. A global function that needs access to private or protected class members must be declared as a friend of that class. A global function must take at least one argument that is of class or enumerated type or that is a reference to a class or enumerated type.


    你违反了其中的第二条,你不可以针对内建数据类型进行操作符重载。 其它条款可以参考以下链接:


    class DoubleType



    double m_Value;

    bool operator < (double& a, double& b)


       return a.m_Value < b.m_Value;



    不过,从你的意图来看,我觉得你重载 ==  根本达不到你的目的。


    2010年3月22日 8:33