friendly operator overloading

Axel Freyn axel-freyn@gmx.de
Mon Feb 23 16:14:00 GMT 2009


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



More information about the Gcc-help mailing list