简体   繁体   中英

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

How would I use a member function (in this case, magnitude() ) within my definition for the function overload of the greater than operator > ? The operator should compare the magnitudes of two objects of the class Vector2D from which magnitude() is also a member. I receive the following:

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;
            }
        }

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

Two changes:

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

All read-only functions should be marked const . You may solve the error by just removing const from parameter of your > operator , but that would not be good.

The problem is that your functions aren't declared const , so can't be applied to constant objects. That's easy to fix:

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

If efficiency is important, you might like to avoid the unnecessary square-root when comparing magnitudes:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM