【发布时间】:2022-01-21 04:07:12
【问题描述】:
以下代码用于在 C++ 中比较两个复数:
#include <iostream>
#include <math.h>
class Complex {
private:
float real;
float imag;
public:
Complex(float realVal, float imagVal): real(realVal), imag(imagVal){}
double magnitude()
{
return sqrt(real*real)+sqrt(imag*imag);
}
friend bool operator<(Complex& c1, Complex& c2)
{
if(c1.magnitude() < c2.magnitude())
{
return true;
}
return false;
}
};
int main()
{
Complex c1(3, 3);
Complex c2(4, 4);
cout << (c2 < c1) << endl;
return 0;
}
但是,由于magnitude(),我无法将operator<() 函数与const 参数一起使用。具体来说,抛出以下错误:error: passing ‘const Complex’ as ‘this’ argument discards qualifiers [-fpermissive]。有什么办法解决这个问题?
【问题讨论】:
-
operator<不修改其运算符,将它们作为const引用传递,并使magnitude也成为常量,它也不会修改this -
将该方法声明为
double magnitude() const。此外,在 that 运算符中,引用 const,例如friend bool operator<(const Complex& c1, const Complex& c2)。 -
注意
if (c1.magnitude() < c2.magnitude()) return true; else return false;通常写成return c1.magnitude() < c2.magnitude();。 -
Complex中operator<使用的唯一部分是magnitude()。magnitude()是 public 成员,因此operator<没有理由成为朋友。此外,对于像Complex这样的小对象,按值传递:bool operator<(Complex c1, Complex c2) { return c1.magnitude() < c2.magnitude(); }。 -
哎呀,
magnitude()看起来不对。如所写,它返回std::abs(real) + std::abs(imag),但计算要冗长得多。大概应该是std::sqrt(real * real + imag * imag);。