Reputation: 29
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?
Upvotes: 0
Views: 89
Reputation:
Even with proper operators
out << c=a <<endl;
which is parsed as
(out << c) = (a <<endl);
the error occurs, due to operator precedence.
Upvotes: 2
Reputation: 27528
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.
Upvotes: 2
Reputation: 6183
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<<
.
Upvotes: 2
Reputation: 9579
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.
Upvotes: 2