friendly operator overloading

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Hi,

I need some help with operator overloading.
Following test program compiles and runs fine with g++ (GCC) 4.1.2:

#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

When I was trying to find out what is going on, I just put s into public.
Then I get the error message:

$ g++  -march=pentium4 -mfpmath=sse   tst.cpp container.cpp container.h  
-o tst
/tmp/ccCAgEWK.o: In function `main':
tst.cpp:(.text+0xb3): undefined reference to
`xxx::operator<<(std::basic_ostream<char, std::char_traits<char> >&,
xxx::Container const&)'
collect2: ld returned 1 exit status
make: *** [tst] Error 1

What makes me believe that there is some trouble with the namespace of the
operator<< definition, but only if I use separate files.

Anybody has any suggestion?

Thank you very much for any help,
-- Bernd

[Index of Archives]     [Linux C Programming]     [Linux Kernel]     [eCos]     [Fedora Development]     [Fedora Announce]     [Autoconf]     [The DWARVES Debugging Tools]     [Yosemite Campsites]     [Yosemite News]     [Linux GCC]

  Powered by Linux