Below is my program, which gives, following errors
c:\mystuff>cl dummy.cpp
Microsoft (R) C/C++ Optimizing Compiler Version 16.00.30319.01 for x64
Copyright (C) Microsoft Corporation. All rights reserved.
dummy.cpp
c:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\INCLUDE\xlocale(323) : wa
rning C4530: C++ exception handler used, but unwind semantics are not enabled. S
pecify /EHsc
dummy.cpp(20) : error C2143: syntax error : missing ';' before '&'
dummy.cpp(20) : error C4430: missing type specifier - int assumed. Note: C++ doe
s not support default-int
dummy.cpp(20) : error C2061: syntax error : identifier 'ostream'
dummy.cpp(20) : error C4430: missing type specifier - int assumed. Note: C++ doe
s not support default-int
dummy.cpp(20) : error C2805: binary 'operator <<' has too few parameters
dummy.cpp(20) : error C2333: 'Complex::operator <<' : error in function declarat
ion; skipping function body
dummy.cpp(32) : error C2065: 'cout' : undeclared identifier
#include<iostream>
class Complex{
private:
double real;
double imag;
public:
Complex(double real, double imag){
this->real = real;
this->imag = imag;
}
Complex operator+ (const Complex& Operand){
double real = this->real + Operand.real;
double imag = this->imag + Operand.imag;
return Complex(real,imag);
}
ostream &operator<< (ostream &o, Complex Operand){//line 20
o << Operand.real;
o << Operand.imag;
return o;
}
};
int main(){
Complex c1(1,2);
Complex c2(3,4);
Complex c3 = c1 + c2;
cout << c3;
}
My question:
1)
At line 32 cout is visible by including extern object cout
from iostream
, so, What is the reason for error at line 32 cout << c3
?
2)
Please help me understand, the reason for error at line #20. operator<<
method is just copied from the book. In addition, I would like to understand why we should pass ostream
reference as first formal parameter in operator<<
method. Because, In operator+
method, i used only one operand as formal parameter by using this
for accessing first operand object. Can't i do the same for operator<<
method by using this
?