I'm working on an assignment for my C++ class at my university. One part of the assignment is to write a Complex number class to learn to learn about operator overloading (hence writing the class, as opposed to simply using c++'s built in Complex number class).
I've got the +, -, and * operators working correctly, but I'm having trouble with the << and >> operators for input and output. Here's the relevant code:
ostream& operator<< ( ostream& out, const Complex& value) {
out << real << " " << value.imaginary;
return out;
}
istream& operator>> ( istream& in, Complex& value) {
double r = 0, i = 0;
in >> r;
in >> i;
value.setReal(r);
value.setImaginary(i);
return in;
}
main.cpp:
#include <Complex.h>
using std::cout;
int main (int argc, char* argv[]) {
//NO OP FOR NOW
}
I'm compiling with g++:
g++ -I. -Wall main.cpp
And the error I receive is:
./Complex.h:30: error: expected constructor, destructor, or type conversion before '&' token
./Complex.h:31: error: expected constructor, destructor, or type conversion before '&' token
I believe it's a problem with the function head of my << and >> functions. However, I've modeled them after a similar example in my textbook, and I've also looked at examples online, and the function heads look identical. If anyone has any ideas what I'm doing syntactically wrong, I'd appreciate it.
Thanks! That was an easy fix. I did find another problem though...
I changed my main to a simple:
#include <Complex.h>
using std::cout;
int main (int argc, char* argv[]) {
Complex com = Complex(4, 4);
cout << com << endl;
}
But now I'm getting the following error:
/tmp/ccuKH5Cr.o: In function `main':
main.cpp:(.text+0x93): undefined reference to `operator<<(std::basic_ostream<char, std::char_traits<char> >&, Complex const&)'
collect2: ld returned 1 exit status
How do I get "cout << com" to reference the << operator that I wrote for Complex?