问题
Here's what I'm trying to do:
class A
{
friend class C (and all of C's derived classes)
public:
void DoAThing() { mpMyC->DelegateResponsibility(myB); }
private:
class B
{
};
B mMyB;
C* mpMyC;
};
class C
{
// No problem here- C can see B
virtual void DelegateResponsibility(const A::B& necessaryInfo);
};
class D: public C
{
// Uh-oh- we don't inherit friendship
virtual void DelegateResonsibility(const A::B& necessaryInfo);
};
In short, I have a private nested class inside A because it's an implementation detail of A. However, I'd like to delegate some responsibilities of A to C and C's derived classes to get some polymorphic behavior. I'd like to avoid having to add a friend class line every time someone derives from C. The standard workaround given for derived friend classes is "just add a protected accessor function to your base class and override it for derived members" but that only helps access private members of class A, not privately scoped classes. Is there any way to workaround this issue?
回答1:
This should work:
class C
{
typedef A::B MyB;
virtual void DelegateResponsibility(const MyB& necessaryInfo);
};
class D: public C
{
// Uh-oh- we don't inherit friendship
virtual void DelegateResonsibility(const MyB& necessaryInfo);
};
回答2:
You could put your class B in a detail namespace, at file scope.
something like this:
namespace my_hidden_area {
class B {
...
}
}
It's not as strong protection as making the class nested private, of course, but it should make it clear to outsiders that they should not be messing around with B.
If you're wondering why friendship is not inheritable, see this question: Why does C++ not allow inherited friendship?
来源:https://stackoverflow.com/questions/23416231/c-allow-derived-classes-of-friend-to-have-access-to-private-nested-class