Overloading Functions Compiler Error

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
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
I'm using code::blocks right now. Isn't it supposed to automatically link the files when it sees the '#include' directive?
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
I created it using notepad++, but I don't see how that makes a difference.
Then you have to manually tell code::blocks to link that specific file.

http://wiki.codeblocks.org/index.php?title=Creating_a_new_project#Changing_file_composition
Last edited on
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.
Thanks!
Topic archived. No new replies allowed.