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


how use member function (in case, magnitude()) within definition function overload of greater operator >? operator should compare magnitudes of 2 objects of classvector2d magnitude() member. receive following:

error c2662: 'double vector2d::magnitude(void)' : cannot convert 'this' >pointer 'const vector2d' '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 initializing             double  magnitude();            // compute , return magnitude             bool operator> (const vector2d& right); // greater                               };          //function definitions:          //default constructor         vector2d::vector2d() {             = 1;             j = 1;          }         /* constructor*/         vector2d::vector2d(double x, double y) {             = x;             j = y;         }          /* magnitude funciton */         double vector2d::magnitude()         {             return sqrt(pow(i, 2) + pow(j, 2));         }         ******* //greater overload ************          bool vector2d::operator> (const vector2d& right) {             if (magnitude() > right.magnitude())             {                 return true;             }             else             {                 return false;             }         }      *********************************************** 

the problem functions aren't declared const, can't applied constant objects. that's easy fix:

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

if efficiency important, might avoid 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(); } 

Comments

Popular posts from this blog

c++ - Difference between pre and post decrement in recursive function argument -

php - Nothing but 'run(); ' when browsing to my local project, how do I fix this? -

php - How can I echo out this array? -