-1

The following code works for comparing two complex numbers in 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;
}

However, I can't the operator<() function to work with const parameters, because of magnitude(). Specifically, the following error is thrown: error: passing ‘const Complex’ as ‘this’ argument discards qualifiers [-fpermissive]. What's the solution to that problem?

asymmetryFan
  • 614
  • 1
  • 10
  • 16

1 Answers1

0

Thanks everyone for the help, here's the working code:

#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;
}

Also, if I remove friend before bool operator<, the code doesn't work. The error that gets printed out is:

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

main.cpp:29:17: error: no match for ‘operator<’ (operand types are ‘Complex’ and ‘Complex’)
asymmetryFan
  • 614
  • 1
  • 10
  • 16
  • 2
    If you remove the `friend` you **also** have to move it outside the class. Otherwise it looks like an odd member function. – BoP Dec 18 '21 at 21:57