| re: Friends and Namespaces
On Mon, 6 Oct 2003 15:14:14 +0100, "Simon" <sorry@no.mail> wrote:
[color=blue]
>Hi,
>
>I have a class Foo which defines a friend function Bar. When I place the Bar
>function within a namespace, I can no longer access the Foo private data
>(i'm guessing it is not recognised as a friend). Could someone explain this
>behaviour, as i'm obviously not understanding namespaces properly.[/color]
You have to declare friendship to the function in the namespace, not
to a non-existent global one.
[color=blue]
>
>Thanks for your help,
>Simon ;o)
>
>//---------------
>
>#include <iostream>[/color]
class Foo;
namespace mynamespace {
int Bar(const Foo& f);
}
[color=blue]
>
>class Foo {
>public:
> Foo() { foo_int = 101; }
>private:
> int foo_int;
> friend Bar(const Foo& f);[/color]
friend mynamespace::Bar(const Foo& f);
[color=blue]
>};
>
>namespace mynamespace {
> int Bar(const Foo& f) {
> return f.foo_int;
> }
>}
>
>int main() {
> Foo f;
> std::cout << mynamespace::Bar(f);
> return 0;
>}[/color]
Tom |