Overloading Operators

I've overloaded the << operator at the bottom of a header file. This is causing LNK2005 and LNK1169 errors both stating multiple definitions.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
//Something.h
#include <iostream>

#ifndef HEADER
#define HEADER

class MyClass
{
	//stuff
};

std::ostream& operator<<(std::ostream &out, const MyClass &c)
{
	//do stuff blah blah blah
	return out;
}

#endif 


This is the only header being included in main. Am I putting the definition in the wrong place? What is causing this?
Definitions do not go in headers. They should be in own compilation usnits.
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
//MyClass.h
#ifndef HEADER
#define HEADER
//Everything in header should be inside guards
#include <iosfwd> //Try to not bring iostream to those not wanting it

class MyClass
{
    //stuff
};

std::ostream& operator<<(std::ostream&, const MyClass&); //Declaration only
#endif 

//Myclass.cpp
#include "MyClass.h"
#include <iostream>

/* Class member definition */

//Operator definition
std::ostream& operator<<(std::ostream& out, const MyClass& c)
{
    //...
    return out;
}

//main.cpp
#include <iostream>
#include "MyClass.h"

int main()
{
    MyClass foo;
    std::cout << foo;
}
Topic archived. No new replies allowed.