recursive friend classes

夙愿已清 提交于 2019-12-19 16:57:07

问题


Is there any way around this:

class B;

class C { 
 public:
  C() { }
 private:
  int i;
  friend B::B();
};

class B { 
 public:
  B() { }
 private:
  int i;
  friend C::C();
};

Gives error:

prog.cpp:8: error: invalid use of incomplete type ‘struct B’
prog.cpp:1: error: forward declaration of ‘struct B’

回答1:


You just can't do this. Remove the circular dependency.




回答2:


According to IBM's documentation (which I realize is not normative):

A class Y must be defined before any member of Y can be declared a friend of another class.

So I think the answer is "no".

Of course, you can use

friend class B;

...instead of friend B::B(), but that grants friendship to all of B's members. And you probably already knew that.




回答3:


Since you're very selective about friendship (access to specific member functions given to specific classes), the Attorney-Client Idiom may be what you need. I'm not sure how well this will work with constructors, though.




回答4:


I realize that this is a really silly idea, but couldn't you—theoretically—accomplish this through inheritance, by making the parent class' constructors friends? The code compiles, at least, questionable though it may be.

class A {
 public:
  A() { }
 private:
  int i;
};

class D {
 public:
  D() { }
 private:
  int i;
};

class B : public A {
 public:
  B() { }
 private:
  friend D::D();
};

class C : public D {
 public:
  C() { }
 private:
  friend A::A();
};


来源:https://stackoverflow.com/questions/6158760/recursive-friend-classes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!