friend class : inherited classes are not friend as well?

天涯浪子 提交于 2019-12-10 17:13:27

问题


In C++, I have a class A which is friend with a class B.

I looks like inherited classes of B are not friend of class A.

I this a limitation of C++ or my mistake ?

Here is an example. When compiling, I get an error on line "return new Memento":

Memento::Memento : impossible to access private member declared in Memento.

class Originator;

class Memento
{
  friend class Originator;

  Memento() {};

  int m_Data;

public:
  ~Memento() {};
};

class Originator
{
public:
  virtual Memento* createMemento() = 0;
};

class FooOriginator : public Originator
{
public:
  Memento* createMemento()
  {
    return new Memento; // Impossible to access private member of Memento
  }
};

void main()
{
  FooOriginator MyOriginator;
  MyOriginator.createMemento();

}

I could of course add FooOriginator as friend of Memento, but then, this means I would have to add all Originator-inherited classes as friend of Memento, which is something I'd like to avoid.

Any idea ?


回答1:


See: Friend scope in C++
Voted exact duplicate.

I looks like inherited classes of B are not friend of class A.

Correct

I this a limitation of C++ or my mistake ?

It is the way C++ works. I don't see it as a limitation.




回答2:


Friendship is not inherited, you have to explicitly declare every friend relationship. (See also "friendship isn't inherited, transitive, or reciprocal")




回答3:


Friendship isn't transitive or inherited. After all, your friend's friend may not be your friend or your father's friends are not your friends in general.




回答4:


The friend directive was originally intended as some "loophole" to bypass the encapsulation mechanism.

With friend you have to specify exactly(!), which classes are your friend. The friendship is not inherited and so FooOriginator has no access to Memento in your example.

But ideally, before you're thinking how to solve your problem with the friend directive, I'd suggest to have a look at your design in general and try to get rid of the need to use friend as it could be seen to live in the same category as our loved goto :)




回答5:


Friendship is not inherited, see http://www.cplusplus.com/doc/tutorial/inheritance.html, What is inherited from the base class?



来源:https://stackoverflow.com/questions/491000/friend-class-inherited-classes-are-not-friend-as-well

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