朋友类:继承类不是朋友吗? [英] friend class : inherited classes are not friend as well?

查看:140
本文介绍了朋友类:继承类不是朋友吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C ++中,我有一个类A,它是类B的朋友。



我看起来继承类B不是类A的朋友。 p>

这是C ++的限制还是我的错误?



这里是一个例子。编译时,我在return new Memento行上遇到错误:



Memento :: Memento:无法访问在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; //不可能访问Memento的私人成员
}
};

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

}



我当然可以添加FooOriginator作为Memento的朋友,但那么,这意味着我必须添加所有Originator继承的类作为Memento的朋友,这是我想避免的。



任何想法? >

解决方案

查看: http://stackoverflow.com/questions/437250/friend-scope-in​​-c/437507

投票的完全相同。

 我看起来继承的B类不是类A的朋友。


b $ b

正确

 我这是C ++的限制还是我的错误? 

这是C ++的工作原理。我不认为这是一个限制。


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 ?

解决方案

See: http://stackoverflow.com/questions/437250/friend-scope-in-c/437507
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.

这篇关于朋友类:继承类不是朋友吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆