Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/149.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
friend类:继承的类也不是friend类? 在C++中,我有一个A类,它是B类的朋友。_C++_Class_Friend - Fatal编程技术网

friend类:继承的类也不是friend类? 在C++中,我有一个A类,它是B类的朋友。

friend类:继承的类也不是friend类? 在C++中,我有一个A类,它是B类的朋友。,c++,class,friend,C++,Class,Friend,看起来继承的B类不是A类的朋友 这是C++的限制还是我的错误?< /P> 这里有一个例子。编译时,我在“return new Memento”(返回新的Memento)行中遇到一个错误: Memento::Memento:无法访问Memento中声明的私人成员 class Originator; class Memento { friend class Originator; Memento() {}; int m_Data; public: ~Memento() {};

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

<>这是C++的限制还是我的错误?< /P> 这里有一个例子。编译时,我在“return new Memento”(返回新的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; // Impossible to access private member of Memento
  }
};

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

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


有什么想法吗?

友谊不是继承的,你必须明确声明每个朋友关系。(另请参见“”)

friend指令最初是用作绕过封装机制的“漏洞”

对于friend,您必须精确地指定(!),哪些类是您的朋友。友谊不是继承的,因此在您的示例中,FooOriginator无法访问Memento


但理想的情况是,在你考虑如何解决你的朋友指令问题之前,我建议你先看看你的设计,试着摆脱使用朋友的需要,因为它可以被视为与我们所爱的goto生活在同一个类别中:)

友谊不是遗传的,请看,从基类继承了什么?

请参阅:
一模一样

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

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

<>这是C++的工作方式。我不认为这是一种限制。

友谊不是传递的,也不是遗传的。毕竟,你朋友的朋友可能不是你的朋友,或者你父亲的朋友通常也不是你的朋友。

我不会说那个朋友和后藤一样坏。当您可以使用它来精简公共接口时,它甚至可以改进封装。然而,这种情况很少发生,太多的朋友破坏了你的私生活。它是在一个逻辑组中封装封装在一起的两个或多个类,但不能被作为一个模块来做,因为没有(并且没有模块级保护):相反,您在C++中使用朋友而不是内部或包级保护。但是我认为它也像Goto:Goto也不坏。但是,在你做其他事情之前,用无数的条件变量强奸你的代码,并用它们扰乱作用域,你只需要使用一个goto并保持你的代码干净。我相信,在友谊的原则上也是如此,但我和你一样,gimpf,朋友——作为后藤——应该被明智地使用和小心地运用。