I have operators declared for class my_type in namespace my_namespace.
namespace my_namespace {
class my_type
{
friend std::ostream& operator << (std::ostream& out, my_type t);
}
}
I'm trying to define these operators in implementation file, but when I write something like that
std::ostream& my_namespace::operator << (std::ostream& out, my_type t)
{
out << t;
return out;
}
I get error message
error: ... operator should have been declared inside 'my_namespace'
When I change it to
namespace my_namespace {
std::ostream& operator << (std::ostream& out, my_type t)
{
out << t;
return out;
}
}
then it's compiles, but I don't understand the problem. Why does this failed to compile? Is there everything right with that? I would appreciate link to standard as I really don't know what to search.
added
file.h
#ifndef A_H
#define A_H
#include <iosfwd>
namespace N
{
class A
{
friend std::ostream& operator << (std::ostream& out, A& obj);
};
}
#endif
file.cpp
#include "file.h"
#include <iostream>
std::ostream& N::operator << (std::ostream& out, N::A& obj)
{
return out;
}
int main() {}
here is complete example. This works fine on VS2010, but gives above mentioned error on gcc 4.4.5.
added
hmm...yes, this one works
namespace N
{
class A
{
friend std::ostream& operator << (std::ostream& out, A& obj);
};
std::ostream& operator << (std::ostream& out, A& obj);
}
I was always thinking that in terms of visibility declaring friend operator in class is same thing as declaring outside of the class..looks like it's not. Thanks.
Thanks much in advance.
-ffriend-injectionwill succeed.