运算符重载时如何调用另一个成员函数(C++)

How to call another member function when operator overloading (C++)

如何在大于运算符 > 的函数重载定义中使用成员函数(在本例中为 magnitude())?运算符应该比较 classVector2D 的两个对象的大小,magnitude() 也是其中的一个成员。我收到以下信息:

error C2662: 'double Vector2D::magnitude(void)' : cannot convert 'this' >pointer from 'const Vector2D' to 'Vector2D &'

 #include <iostream>
        #include <math.h>
        #include <string>
        using namespace std;

        //***************************  Class Definition  ***************************

        class Vector2D {
        public:
            double i, j;
            Vector2D();                     // Default constructor
            Vector2D(double, double);       // Constructor for initializing
            double  magnitude();            // compute and return the magnitude
            bool operator> (const Vector2D& right); // greater than                      
        };

        //function definitions:

        //default constructor
        Vector2D::Vector2D() {
            i = 1;
            j = 1;

        }
        /* constructor*/
        Vector2D::Vector2D(double x, double y) {
            i = x;
            j = y;
        }

        /* magnitude funciton */
        double Vector2D::magnitude()
        {
            return sqrt(pow(i, 2) + pow(j, 2));
        }

       ******* //greater than Overload ************

        bool Vector2D::operator> (const Vector2D& right) {
            if (magnitude() > right.magnitude())
            {
                return true;
            }
            else
            {
                return false;
            }
        }

    ***********************************************

两个变化:

  • bool Vector2D::operator> (const Vector2D& right) const
  • double Vector2D::magnitude() const

所有只读函数都应标记为const。您可以通过从 > operator 的参数中删除 const 来解决错误,但这并不好。

问题是您的函数未声明 [​​=12=],因此不能应用于常量对象。这很容易修复:

double  magnitude() const;
bool operator> (const Vector2D& right) const;

如果效率很重要,您可能希望在比较幅度时避免不必要的平方根:

double square_magnitude() const {return i*i + j*j;}
bool operator> (const Vector2D& right) const {
    return square_magnitude() > right.square_magnitude();
}