This is the mail archive of the
gcc-help@gcc.gnu.org
mailing list for the GCC project.
Re: friendly operator overloading
- From: Axel Freyn <axel-freyn at gmx dot de>
- To: gcc-help at gcc dot gnu dot org
- Date: Mon, 23 Feb 2009 17:20:16 +0100
- Subject: Re: friendly operator overloading
- References: <470cb4e0e9f0fb26fd9dac501dcf288d@prager.ws>
Hi Bernd,
for me (g++ 4.2.1) it runs in both situations.
On Mon, Feb 23, 2009 at 08:09:22AM -0700, Bernd Prager wrote:
> #include <iostream>
> #include <string>
> namespace xxx
> {
> class Container
> {
> friend std::ostream &operator<<(std::ostream&, const Container&);
> private:
> int id;
> std::string s;
> public:
> Container() : s("Hello World") {}
> };
> std::ostream &operator<<(std::ostream &stream, const Container &c)
> {
> return std::cout << c.s << std::endl;
> }
> } // namespace
> using namespace xxx;
> int main()
> {
> Container* c = new Container();
> std::cout << *c;
> return 0;
> }
>
> As long as I use it one (!) source file.
>
> When I separate the Container class in separate Container.h and a
> Container.cpp files the compiler complains about:
> $ g++ -march=pentium4 -mfpmath=sse tst.cpp container.cpp container.h
> -o tst
> container.h: In function âstd::ostream& operator<<(std::ostream&, const
> xxx::Container&)â:
> container.h:13: error: âstd::string xxx::Container::sâ is private
> container.cpp:8: error: within this context
> make: *** [tst] Error 1
I suspect this is a problem how you defined operator <<. It works with
the following files ( operator << is defined OUTSIDE namespace xxx, and
before it is used in class Container):
container.h:
namespace xxx{
class Container;
}
std::ostream &operator<<(std::ostream&, const xxx::Container&);
namespace xxx
{
class Container
{
friend std::ostream &::operator<<(std::ostream&, const xxx::Container&);
private:
int id;
std::string s;
public:
Container();
};
}
container.cpp:
#include "container.h"
namespace xxx
{
Container::Container() : s("Hello World") {}
}
std::ostream &operator<<(std::ostream &stream, const xxx::Container &c)
{
return std::cout << c.s << std::endl;
}
test.cpp:
#include "container.h"
using namespace xxx;
int main()
{
Container* c = new Container();
std::cout << *c;
return 0;
}
Of course, it is also possible to define operator << inside the
namespace.
HTH - if not, it would be useful if you could send the three seperated
files you used,
Axel