class X { int a; friend void friend_set(X*, int); public: void member_set(int); }; void friend_set(X* p, int i) { p->a = i; } void X::member_set(int i) { a = i; } void f() { X obj; friend_set(&obj,10); obj.member_set(10); }
class A { class B { }; friend class X; }; struct X : A::B { // OK: A::B accessible to friend A::B mx; // OK: A::B accessible to member of friend class Y { A::B my; // OK: A::B accessible to nested member of friend }; };
class X { enum { a=100 }; friend class Y; }; class Y { int v[X::a]; // OK, Y is a friend of X }; class Z { int v[X::a]; // error: X::a is private };
class A {
friend class B { }; // error: cannot define class in friend declaration
};
friend elaborated-type-specifier ; friend simple-type-specifier ; friend typename-specifier ;
class C; typedef C Ct; class X1 { friend C; // OK: class C is a friend }; class X2 { friend Ct; // OK: class C is a friend friend D; // error: no type-name D in scope friend class D; // OK: elaborated-type-specifier declares new class }; template <typename T> class R { friend T; }; R<C> rc; // class C is a friend of R<C> R<int> Ri; // OK: "friend int;" is ignored
class Y { friend char* X::foo(int); friend X::X(char); // constructors can be friends friend X::~X(); // destructors can be friends };
class M { friend void f() { } // definition of global f, a friend of M, // not the definition of a member function };
class A { friend class B; int a; }; class B { friend class C; }; class C { void f(A* p) { p->a++; // error: C is not a friend of A despite being a friend of a friend } }; class D : public B { void f(A* p) { p->a++; // error: D is not a friend of A despite being derived from a friend } };
class X; void a(); void f() { class Y; extern void b(); class A { friend class X; // OK, but X is a local class, not ::X friend class Y; // OK friend class Z; // OK, introduces local class Z friend void a(); // error, ::a is not considered friend void b(); // OK friend void c(); // error }; X* px; // OK, but ::X is found Z* pz; // error, no Z is found }