[英]How to call another member function when operator overloading (C++)
我如何在定义中使用成员函数(在这种情况下, magnitude()
)来实现大于操作符>
的函数重载? 操作员应比较Vector2D
类的两个对象的大小,这些对象也属于Vector2D
magnitude()
。 我收到以下信息:
错误C2662:'double Vector2D :: magnitude(void)':无法将'this'>指针从'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 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
来解决错误,但这并不好。
问题在于您的函数未声明为const
,因此无法应用于常量对象。 很容易解决:
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();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.