0

I wrote the following test program:

 int main(int argc, char** argv)
   {

    ifstream inFile;
    inFile.open("D:\\C++\\Assignments\\in1.txt");
    if (!inFile) {
            cout << "Unable to open file";
            exit(1); // terminate with error
    }
    Complex a,b,c;
    inFile >> a;
    inFile >> b;
    ofstream out;
    out.open("D:\\C++\\Assignments\\out1.txt");
    out << a <<endl<< b<<endl;  // dumps data to a stream connected to a file
    out << c=a <<endl;
    out.close();



  return 0;
  }

I have overloaded = as following:

  void Complex::operator=(const Complex &a)//mulptiplication
  {
    real=a.real;
    imag=a.imag;
   }

But I am getting errors like: no match for ooperator <<. Can anyone help with the error?

L.G
  • 29
  • 5

4 Answers4

2

This is your problem:

out << c=a <<endl;

You need to return a Complex&

Try this:

Complex& Complex::operator=(const Complex &a)//mulptiplication
{
  real=a.real;
  imag=a.imag;

  return *this;
}

The reason is that c=a yields a void and there is no operator<< that works for void on the left hand side

Just for clarity, you might rewrite as:

c = a;
out << c << endl;

ortang is also right that there must be an operator<< for the Complex class.

Josh Petitt
  • 9,371
  • 12
  • 56
  • 104
  • Thanks @Josh, I tried it but I m getting error that it must be a nonstatic memeber function. – L.G Mar 28 '14 at 18:56
2

The problem lies in out << a << endl << b << endl, since you did not overload the operator<< for the Complex class i guess.

Take a look at this SO post how to overload the operator<<.

Community
  • 1
  • 1
Ortwin Angermeier
  • 5,957
  • 2
  • 34
  • 34
  • I have defined them in the cpp file. The question is concerning,= operator. However thank you for pointing it out,it is my fault not to post my cpp file. – L.G Mar 28 '14 at 18:59
2

If real and imag are themselves of types with correct assign semantics (for example primitive types like int or double), then it is redundant and error-prone to implement your own operator=. Just use the compiler-generated one.

Christian Hackl
  • 27,051
  • 3
  • 32
  • 62
2

Even with proper operators

out << c=a <<endl;

which is parsed as

(out << c) = (a <<endl);

the error occurs, due to operator precedence.