By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
454,465 Members | 1,600 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 454,465 IT Pros & Developers. It's quick & easy.

Problem overloading <<

P: n/a
Hi,

Describing this problem will be a bit long winded, but please bear
with me:

I've got three files in my project: permuts.h, permuts.cpp, and
braids.cpp (some content from wich will eventually be moved into
braids.h). Both cpp files include the h file. Permuts.h contains the
Permutation class, for which I needed to overload <<. Doing this in
that file caused an error(Duplicate definition I think - it occurs to
me now to try #ifndef on this) so I moved it to permuts.cpp. But it
wouldn't compile (The error message from GNU C++ was HUGE!) unless I
deleted it from permuts and put it in braids (which also housed main()
- and no, it couldn't ccompile when the overloaded << was in both CPP
files.)

Can anyone explain why it won't go in permuts.cpp (even if the answer
is I should have used #ifndef and put it in the .h)

Thanks,

James McLaughlin.
Jul 29 '05 #1
Share this Question
Share on Google+
2 Replies


P: n/a
Why not declare the function (as a prototype) in the header file
(permuts.h) and define it in permuts.cpp. Thus:

// in permuts.h:
std::ostream & operator<<( ostream &, const Permutation & );

// in permuts.cpp
std::ostream & operator<<( ostream & os, const Permutation & perm)
{
// body here
return os;
}

If you want this function to access private members of Permutation,
thus be a friend, then Permutation.h should look like:

// in permuts.h:
#ifndef PERMUTATION_INCLUDED
#define PERMUTATION_INCLUDED

class Permutation; // forwardly declare Permutation

std::ostream & operator<<( ostream &, const Permutation & );

class Permutation
{
friend std::ostream & operator<<( ostream &, const Permutation & );
// class definition here
};

#endif

Jul 29 '05 #2

P: n/a
Thanks Earl, your suggestion solved the problem!

On 29 Jul 2005 08:33:28 -0700, "Earl Purple" <ea*********@yahoo.com>
wrotE:
Why not declare the function (as a prototype) in the header file
(permuts.h) and define it in permuts.cpp. Thus:

// in permuts.h:
std::ostream & operator<<( ostream &, const Permutation & );

// in permuts.cpp
std::ostream & operator<<( ostream & os, const Permutation & perm)
{
// body here
return os;
}

Aug 1 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.