When i try to overload the "<<" operator in my .h file, i get the following error:
multiple definition of `operator<<(std::ostream&, complex_number&)'
But when i move my operator overloading in my .cpp file, everything works just fine. I don't really know what is happening. Any help?
Here is my initial code:
(main.cpp is really simple and does not contain anything important)
complex_number.h
#ifndef COMPLEX_NUMBER_H
#define COMPLEX_NUMBER_H
#include <iostream>
using namespace std;
class complex_number
{
public:
complex_number();
complex_number(double, double);
virtual ~complex_number();
double Geta() const { return a; }
void Seta(double val) { a = val; }
double Getb() const { return b; }
void Setb(double val) { b = val; }
void print();
friend ostream & operator << (ostream &out, complex_number &cmp);
protected:
private:
double a;
double b;
};
ostream & operator << (ostream &out, complex_number &cmp) {
double a = cmp.Geta();
double b = cmp.Getb();
if (a == 0 && b == 0){
out << "0";
}
else if (a == 0) {
//if (b < 0) cout << "-";
if (b == -1) {
out << "-i";
}
if (b!=1) cout << b;
out << "i";
}
else if (b == 0) {
out << a;
} else {
out << a;
out << (b > 0 ? "+" : "-");
if (b!=1 && b!=-1) out << (b > 0 ? b : -1*b);
out << "i";
}
return out;
}
#endif // COMPLEX_NUMBER_H
complex_number.cpp
#include "complex_number.h"
#include <iostream>
#include <string>
using namespace std;
complex_number::complex_number()
{
//ctor
a = 0;
b = 0;
}
complex_number::complex_number(double a1, double b1)
{
//ctor
a = a1;
b = b1;
}
void complex_number::print() {
if (a == 0 && b == 0){
cout << "0";
return;
}
else if (a == 0) {
//if (b < 0) cout << "-";
if (b == -1) {
cout << "-i";
return;
}
if (b!=1) cout << b;
cout << "i";
return;
}
else if (b == 0) {
cout << a;
return;
}
cout << a;
cout << (b > 0 ? "+" : "-");
if (b!=1) cout << (b > 0 ? b : -1*b);
cout << "i";
return;
}
complex_number::~complex_number()
{
//dtor
}