multiply defined operator

B

Brett Irving

Hi I keep having problems with trying to overload the << operator,
the compiler will not let me define it.

the code looks like

#ifndef __MYARRAY_H__
#define __MYARRAY_H__
#include <iostream>
..
..
..
..
};

ostream & operator<<(ostream &o, MyArray& m)
{
return m(o);
}

#endif

It wont work if I put it inside or out of the #endif

The error that the compiler keeps giving me is this.

ld: fatal: symbol `operator<<(std::basic_ostream<char,
std::char_traits<char> >&, MyArray&)' is multiply defined:
(file MyArrayMain.o and file MyArray.o);
ld: fatal: File processing errors. No output written to myarray
collect2: ld returned 1 exit status



Please help.
thanks a lot
 
J

John Harrison

Brett Irving said:
Hi I keep having problems with trying to overload the << operator,
the compiler will not let me define it.

the code looks like

#ifndef __MYARRAY_H__
#define __MYARRAY_H__
#include <iostream>
.
.
.
.
};

ostream & operator<<(ostream &o, MyArray& m)

Should be

inline ostream & operator<<(ostream &o, MyArray& m)

Also you are ignoring the issue of const, you should write

inline ostream & operator<<(ostream &o, const MyArray& m)

because you don't change a MyArray when you output it. Although making this
change will probably mean that you have to stop ignoring the issue of const
in the declaration of MyArray as well. Look on it as a good oppurtunity to
learn about const.

john
 
A

Aggro

Brett said:
#ifndef __MYARRAY_H__
#define __MYARRAY_H__

C++ standard specifically reserves macros with two sequential
underscores for use by the implementation. In most cases, there is no
problem, but if you want your code to be portable... You will propably
do just fine if you write only:

#ifndef MYARRAY_H
#define MYARRAY_H
 
B

Brett Irving

Thanks Heaps



John Harrison said:
Should be

inline ostream & operator<<(ostream &o, MyArray& m)

Also you are ignoring the issue of const, you should write

inline ostream & operator<<(ostream &o, const MyArray& m)

because you don't change a MyArray when you output it. Although making this
change will probably mean that you have to stop ignoring the issue of const
in the declaration of MyArray as well. Look on it as a good oppurtunity to
learn about const.

john
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,996
Messages
2,570,238
Members
46,826
Latest member
robinsontor

Latest Threads

Top