Overloading ostream operator confusion

I'm hoping someone can help clarify something for me here-I've done some digging around and I'm still confused as to why this isn't working.

I have a class that's in a namespace, and I'd like to overload the ostream operator to print some parameters that class holds in a formatted fashion. As a test I have (keeping things to a minimum):

parameterfile.h:
1
2
3
4
5
namespace see{
  class ParameterFile{
    friend std::ostream &operator<<(std::ostream &, const see::ParameterFile &);
  };
};


parameterfile.cc
1
2
3
4
5
6
7
using namespace std;
using namespace see;

std::ostream &operator<<(std::ostream &output, const see::ParameterFile &param){
  output << "Overload test" << endl;
  return output;
}


Now I have a function that's calling it like:
1
2
3
4
5
void nddo(){
  ParameterFile param;

  cout << param << endl;
}


Both parameterfile.cc and nddo.cc compile fine. However, when I get to linking all my object files together I get:

 
nddo.cc:(.text+0x846): undefined reference to `see::operator<<(std::basic_ostream<char, std::char_traits<char> >&, see::ParameterFile const&)' 


Can anyone comment on what I might be doing wrong?
You're putting your function body in the global namespace, not in the 'see' namespace.

Change it to this:

parameterfile.cc
1
2
3
4
5
6
7
8
9
10
11
12
using namespace std;
//using namespace see;  <- bad

namespace see  // <- good
{

std::ostream &operator<<(std::ostream &output, const see::ParameterFile &param){
  output << "Overload test" << endl;
  return output;
}

} // namespace see 



As a general rule of thumb, using namespace xxx works for when you want to use things in the xxx namespace. When adding/modifying/defining things in the xxx namespace, you need actually be inside the namespace (ie: namespace xxx { } )
Last edited on
Ah that makes sense-I did that and it's now working like I wanted :)

Thanks!
Topic archived. No new replies allowed.