0

I have to do 2 functions for overloaing x-complex and complex-x operators.for this, I do not have to use friend functions. Can you suggest how I can do X - complex overload without friend function?

My code

//overload obj - x operator
    ComplexNumber operator-(int x) {
        ComplexNumber temp(0, 0);
        temp.real = real - x;
        temp.imag = imag;
        return temp;
    }

  //overload x-obj operator
    friend ComplexNumber operator-(int x, const ComplexNumber &c) {
        ComplexNumber temp(0, 0);
        temp.real = x - c.real;
        temp.imag = -c.imag;
        return temp;
    }
sdblog 22
  • 23
  • 6
  • Define it as a non-friend function, outside of the class, and without the `friend` specifier? – Some programmer dude Oct 24 '22 at 10:45
  • I thought about it. But, isn't there a way for the function to remain a member of the class? – sdblog 22 Oct 24 '22 at 10:47
  • 1
    When you declare a friend function, it's not actually a "member" of the class, even if defined (implemented) inline inside the class. And no, if you don't want to make it a friend function, then you can't declare or define it inside the class. – Some programmer dude Oct 24 '22 at 10:54
  • Does this answer your question? [What are the basic rules and idioms for operator overloading?](https://stackoverflow.com/questions/4421706/what-are-the-basic-rules-and-idioms-for-operator-overloading) – Richard Critten Oct 24 '22 at 11:21
  • If you first implement unary negation of complex numbers (which you will need sooner or later), `ComplexNumber operator-(int x, const ComplexNumber &c) { return -c + x; }`. – molbdnilo Oct 24 '22 at 11:21

0 Answers0