Feb 16, 2014 at 2:12am UTC
I'm trying to overload the '<<' and '>>' operators but when I compile using g++, it gives me the following error messages:
'undefined reference to operator>>(std::istream&, myComplex&)' and
'undefined reference to operator<<(std::ostream&, myComplex)'
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
"myComplex.h"
#include <iostream>
class myComplex{
double real;
double imag;
public :
myComplex(){};
myComplex(double r, double i) : real(r), imag(i){};
myComplex operator + (const myComplex& in);
myComplex operator - (const myComplex& in);
myComplex operator * (const myComplex& in);
friend std::ostream &operator <<(std::ostream &out, myComplex c);
friend std::istream &operator >>(std::istream &in, myComplex &c);
};
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
"myComplex.cpp
#include " myComplex.h"
myComplex myComplex:: operator+ (const myComplex& in){
double result_real = real + in.real;
double result_imag = imag + in.imag;
return myComplex (result_real, result_imag);
}
myComplex myComplex:: operator- (const myComplex& in){
double result_real = real - in.real;
double result_imag = imag - in.imag;
return myComplex (result_real, result_imag);
}
myComplex myComplex:: operator* (const myComplex& in){
double result_real = real * in.real;
double result_imag = imag * in.imag;
return myComplex (result_real, result_imag);
}
std::ostream &operator<<(std::ostream &out, myComplex c)
{
out<<" real part: "<<c.real<<" \n";
out<<" imag part: "<<c.imag<<" \n";
return out;
}
std::istream &operator>>(std::istream &in, myComplex &c)
{
std::cout<<" enter real part:\n";
in>>c.real;
std::cout<<" enter imag part: \n";
in>>c.imag;
return in;
}
1 2 3 4 5 6 7 8 9 10 11
"main.cpp"
#include "myComplex.h"
using namespace std;
int main()
{
myComplex a;
cin>>a;
cout<<a;
}
Last edited on Feb 16, 2014 at 3:31am UTC
Feb 16, 2014 at 3:34am UTC
Works for me.
enter real part:
1
enter imag part:
2
real part: 1
imag part: 2
So probably you haven't linked myComplex.cpp with main.cpp.
Last edited on Feb 16, 2014 at 3:35am UTC
Feb 16, 2014 at 3:58am UTC
I'm using code::blocks right now. Isn't it supposed to automatically link the files when it sees the '#include' directive?
Feb 16, 2014 at 4:09am UTC
I think code::blocks will link automatically, but only if you create the file through code::blocks, did you create the file yourself?
Last edited on Feb 16, 2014 at 4:09am UTC
Feb 16, 2014 at 4:52am UTC
I created it using notepad++, but I don't see how that makes a difference.
Feb 16, 2014 at 5:05am UTC
Last edited on Feb 16, 2014 at 5:08am UTC
Feb 16, 2014 at 5:10am UTC
How do I go about doing that? I'm not too familiar yet with the program. I have the latest version of Code::Blocks by the way.