Multiple operator definitions

Hi I have a very simple test case which I am trying to solve.
I have the following classes and files:

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
38
39
/***   MyClass.h ***/

#ifndef MYCLASS
#define MYCLASS
#include <ostream>
#include <iostream>

class MyClass
{
	public:
		MyClass();
		void print(std::ostream& os = std::cout) const
		{
			os << "Hello" <<std::endl;
		}
	
};
std::ostream& operator<<(std::ostream& os,const MyClass& col);
#endif
/******END MyClass.h***/

/*** MyClass.cpp ***/
#include "MyClass.h"
MyClass::MyClass(){}
std::ostream& operator<<(std::ostream& os,const MyClass& col)
{
	col.print(os);
}
/****END MyClass.cpp ***/

/*** main.cpp***/
#include "MyClass.h"
int main()
{
    MyClass a;
}

/**END main.cpp***/



Linking causes the error: multiple definitions of operator<<(ostream&,MyClass&)

And I simple cannot understand why because it is not defined in the header file!

The obvious solution is to place the entire operator in the header file and declare it inline, but there must be some other way. What is the correct way of defining global overloaded operators?

Thanks
I don't get that error. But your operator function should return the argument stream:
1
2
3
4
5
std::ostream& operator<<(std::ostream& os,const MyClass& col)
{
        col.print(os);
        return os;
}

Hope this helps.
Okay it seems I was having one of those days. It probably has something to do with not cleaning the old object files, but now it works and I am unable to recreate the error.

Thanks for the help
Topic archived. No new replies allowed.