I want to make an inner class a friend of an unrelated class but this doesn't seem to work (at least in gcc 4.1.2):
class A {
int i;
friend class B; // fine
friend class B::C; 开发者_运维知识库// not allowed?
};
class B {
int geti(A* ap) { return ap->i; }
class C {
int geti(A* ap) { return ap->i; }
};
};
You have to declare B::C
before using it. The following might work.
Update: Ignoring a usable demonstration as requested, here's a way of structuring this (minus the definitions of member functions) that could work, but bear in mind that everything is private as it stands.
class A;
class B
{
int geti(A * ap);
public:
class C
{
int geti(A * ap);
};
};
class A
{
friend class B; // fine
friend class B::C; // fine too
int i;
};
Then define the getter functions elsewhere:
int B::geti(A * ap) { ... }
int B::C::geti(A * ap) { ... }
Alternative: forward-declare the nested class B::C
and save one external definition:
class A;
class B
{
int geti(const A * ap) const; // we cannot use A yet!
public:
class C;
};
class A
{
friend class B; // fine
friend class B::C; // fine too
int i;
};
int B::geti(const A * ap) const { return ap->i; }
class B::C
{
inline int geti(const A * ap) const { return ap->i; }
};
精彩评论