Reputation: 571
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 classVector2D
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;
}
}
***********************************************
Upvotes: 0
Views: 161
Reputation: 254431
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();
}
Upvotes: 1
Reputation: 18411
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.
Upvotes: 1