friendly operator overloading
Bernd Prager
bernd@prager.ws
Mon Feb 23 15:10:00 GMT 2009
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
More information about the Gcc-help
mailing list