C++ Error: Structs operator for negation (-) [closed]

  c++, negation, operator-keyword, struct

I’m trying to make a complex number calculator, and trying to use structs to define them. Now I wanna implement the negation operand (-) for just a single complex number. This would be just the code for the negation operator:

Complex operator-(Complex &a){
  Complex result;
  result.real = -a.real;
  result.imag = -a.imag;
  return result;
} 

This is the rest of the code:

#include "complex.h"


std::istream & operator>>(std::istream & in, Complex & a) {
    if(!read_input(in, a)) {
        in.setstate(std::ios::failbit);
    }
    return in;
}

Complex operator+(Complex &a, Complex &b){
  Complex result;
  result.real = a.real +b.real;
  result.imag = a.imag +b.imag;
  return result;
}

Complex operator-(Complex &a, Complex &b){
  Complex result;
  result.real = a.real -b.real;
  result.imag = a.imag -b.imag;
  return result;
}

Complex operator*(Complex &a, Complex &b){
  Complex result;
  result.real = (a.real*b.real)-(a.imag*b.imag);
  result.imag = (a.real*b.imag)+(b.real*a.imag);
  return result;
}

Complex operator/(Complex &a, Complex &b){
  Complex result;
  result.real = ((a.real*b.real)+(a.imag*b.imag))/(b.real*b.real)+(b.imag*b.imag);
  result.imag = ((b.real*a.imag)-(a.real*b.imag))/(b.real*b.real)+(b.imag*b.imag);
  return result;
}

Complex operator-(Complex &a){
  Complex result;
  result.real = -a.real;
  result.imag = -a.imag;
  return result;
}

bool operator==(Complex &a, Complex &b){
  if (same(a,b)){
    return true;
  }
  else {
    return false;
  }
}

bool operator!=(Complex &a, Complex &b){
  if (same(a,b)){
    return false;
  }
  else {
    return true;
  }
}

/*
std::ostream & Complex::output(std::ostream& out){
  if (a.imag > 0){
    return out << '(' << a.real << '+' << a.imag << "i)";
  }
  else if (a.imag ==0){
    return out << a.real ;
  }
  else {
    return out <<'(' << a.real << a.imag << "i)"
  }
} */


std::ostream& operator<<(std::ostream& out, Complex& a){
  if (a.imag > 0){
    return out << '(' << a.real << '+' << a.imag << "i)";
  }
  else if (a.imag ==0){
    return out << a.real ;
  }
  else {
    return out <<'(' << a.real << a.imag << "i)";
  }
}


bool read_input(std::istream &in, Complex &a){
  char c;
  std::cin.get() >> c;
  if (c != '[') return false;
  std::cin >> a.real;
  std::cin.get() >> c;
  if (c != ',') return false;
  std::cin >> a.imag;
  std::cin.get() >> c;
  if (c != ']') return false;
  return true;
}

bool same(Complex &a, Complex &b){
  if ((b.real-0.005 <= a.real && a.real <=b.real+0.005)  && (b.imag-0.005 <=a.imag && a.imag <=b.imag+0.005)){
    return true;
  }
  else {
    return false;
  }
}

Also, I’m not sure if my input operator works, but that’s a different story…

Source: Windows Questions C++

LEAVE A COMMENT