【问题标题】:C++ how to overload operator < for complex numbers?C ++如何为复数重载运算符<?
【发布时间】: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&lt;() 函数与const 参数一起使用。具体来说,抛出以下错误:error: passing ‘const Complex’ as ‘this’ argument discards qualifiers [-fpermissive]。有什么办法解决这个问题?

【问题讨论】:

  • operator&lt; 不修改其运算符,将它们作为const 引用传递,并使magnitude 也成为常量,它也不会修改this
  • 将该方法声明为double magnitude() const。此外,在 that 运算符中,引用 const,例如 friend bool operator&lt;(const Complex&amp; c1, const Complex&amp; c2)
  • 注意if (c1.magnitude() &lt; c2.magnitude()) return true; else return false;通常写成return c1.magnitude() &lt; c2.magnitude();
  • Complexoperator&lt; 使用的唯一部分是magnitude()magnitude()public 成员,因此 operator&lt; 没有理由成为朋友。此外,对于像Complex 这样的小对象,按值传递:bool operator&lt;(Complex c1, Complex c2) { return c1.magnitude() &lt; c2.magnitude(); }
  • 哎呀,magnitude() 看起来不对。如所写,它返回std::abs(real) + std::abs(imag),但计算要冗长得多。大概应该是std::sqrt(real * real + imag * imag);

标签: c++ operator-overloading


【解决方案1】:

感谢大家的帮助,这里是工作代码:

#include <iostream>
#include <math.h>

using namespace std;

class Complex {
private:
    float real; 
    float imag; 
public:
    Complex(float realVal, float imagVal): real(realVal), imag(imagVal) {}

    double magnitude() const
    {
        return sqrt(real * real + imag * imag);
    }

    friend bool operator<(const Complex& c1, const Complex& c2)
    {
        return c1.magnitude() < c2.magnitude();
    }
};

int main()
{
    Complex c1(3, 3);
    Complex c2(4, 4);
    cout << (c2 < c1) << endl;

    return 0;
}

另外,如果我在bool operator&lt; 之前删除friend,则代码不起作用。打印出来的错误是:

main.cpp: In function ‘int main()’:

main.cpp:29:17: error: no match for ‘operator<’ (operand types are ‘Complex’ and ‘Complex’)

【讨论】:

  • 如果你删除了friend,你必须把它移到课堂之外。否则它看起来像一个奇怪的成员函数。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-10-27
  • 2012-12-22
  • 2016-09-26
  • 2012-04-21
  • 1970-01-01
  • 1970-01-01
  • 2010-09-30
相关资源
最近更新 更多