友元类继承 [英] friend class with inheritance

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

问题描述

如果我有两个继承类如下:

  class A 
{
.. 。
}

class B:public A
{
...
}

第三个类定义为A类朋友:

  class C 
{
friend class A;
}

我是否可以从 / code>(其也是 A 类型的对象)类C 的所有成员,已经定义 class B 首先是朋友Class?

解决方案

friend ship既不是继承也不是可传递的。它是两个类之间严格一对一的关系。

  A类{
朋友class B;
int Aries;
};

class B {
friend class C;
int Taurus;
};

class C {
int Leo;
void Capricorn(){
A a;
a.Aries = 0; // this wont work,C is not a friend of A.
//友谊不是传递的
}
};

class D:public C {
void Gemini(){
B b;
b.Taurus = 0; // this wont work,D不是B的朋友。
//友谊不是继承的
}
};

class E:public B {
void Scorpio(){
C c;
c.Leo = 0; // this wont work either,friendship is not inherited
}
};

参考:C ++编程语言Bjarne Stroustrup



更多解释(我的):如果 friend 船不是一对一,它将是封装的结束。请注意, B 类只能访问 A 的成员 private 如果 A 的类声明将 B 声明为 friend B 不能强制朋友 A >

现在,如果友谊可以继承,那么有人只需要继承 B 即可访问 A ,没有 A 在阻止它。此外,允许 friend 是可传递的会导致其他问题,因为现在 B 可能有 friend C ,他们可以有朋友 D ,一直到 Z 。所有 B C D ,... , Z 现在可以访问 A 私人这将是一场灾难。


If I have two Classes as follows with inheritance:

class A
{
    ...
}

class B : public A
{
    ...
}

And a third class with defined as a friend class A:

class C
{
    friend class A;
}

Will I be able to access from class B (which is also an object of type A) all members of class C as if I had defined class B the friend Class in the first place?

解决方案

friendship is neither inherited nor transitive. It is strictly one-one relationship between two classes.

class A {
  friend class B;  
  int Aries;
};

class B {
  friend class C;  
  int Taurus;
};

class C {
  int Leo;
  void Capricorn() {
    A a;
    a.Aries = 0;  // this wont work, C is not a friend of A.
                // friendship is not transitive
  }
};

class D : public C {
  void Gemini() {
    B b;
    b.Taurus = 0;  // this wont work, D is not a friend of B.
                   // friendship is not inherited
  }
};    

class E : public B {
  void Scorpio() {
    C c;
    c.Leo = 0; // this wont work either, friendship is not inherited
  }
};

Reference: "The C++ Programming Language" Bjarne Stroustrup

More explanation (mine): If friendship were not one-one, it would be the end of encapsulation. Note that B class can access private members of A only if the class declaration of A declares B as friend. B cannot enforce friendship on A.

Now, if friendship could be inherited, then someone just needs to inherit B to access private members of A, without A having any say in preventing it. Also, allowing friendship to be transitive would lead to other problems, since now B could have a friend C, who in turn could have a friend D, all the way to Z. All of B, C, D, ..., Z can now access A's private members, which would be a disaster.

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

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