Consider a class inside a namespace. The definition of the class declares a friend function.
namespace Foo
{
class Bar
{
friend void baz();
};
}
This should, based on what I know, declare baz()
as a member of the innermost enclosing namespace, i.e. Foo
.
Therefore, I expected the following definition for baz()
to be correct:
void Foo::baz() { }
However, GCC (4.7) gives me an error.
error: ‘void Foo::baz()’ should have been declared inside ‘Foo’
Several solutions seem to work:
Declare baz()
outside the class.
namespace Foo
{
void baz();
class Bar
{
friend void baz();
};
}
Define baz()
inside the namespace.
namespace Foo
{
class Bar
{
friend void baz();
};
}
...
namespace Foo
{
void baz() { }
}
Compile with the -ffriend-injection
flag, which eliminates the error.
These solutions seem to be inconsistent with the general rules of declaration/definition in C++ I know.
Why do I have to declare baz()
twice?
Why is the definition otherwise only legal inside a namespace, and illegal with the scope resolution operator?
Why does the flag eliminate the error?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…