关于继承

本文通过C++示例代码详细解析了基类不同访问描述符(private、protected、public)对于派生类成员函数及友元函数访问权限的影响,并展示了不同类型指针之间的转换规则。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

对于基类的访问描述符控制着对基类成员的访问,以及从派生
类型到基类类型的指针、引用转换,如冲基类 B 派生类 D :
如果 B 是 private 基类,则其 public 和 protected 成员只能由 D 的
成员函数和友元访问;只有 D 的成员和友元能将 D* 转换到 B*
如果 B 是 protected 基类,则其 public 和 protected 成员只能由 D
的成员函数和友元、以及 D 的派生类的成员函数和友元访问;只
有 D 的成员和友元以及 D 的派生类的成员函数和友元能将 D* 转
换成 B*
如果 B 是 public 基类,则其 public 成员可以由任何函数使用,除
此之外,其 protected 成员还能由 D 的成员函数和友元,以及 D
的派生类的成员函数和友元访问;任何函数都可将 D* 转换到 B*
 

#include <iostream>
using namespace std;

class A
{
public:
    A()
 {
  cout<<"A()---------";
 }
 void print()
 {
  cout << "AAAAAAAAAAAAA" << endl;
 }
private:
 int ival;
};

class B:private A
{
public:
 B()
 {
  cout<<"B()--------------------"<<endl;
 }
 friend void print_1(B* pb);
 friend void print2(B*c);

private:
 double dval;
};
 void print_1(B* pb)
{
 cout << "BBBBBBBBBBBBBB" << endl;
 A* p = pb;
 p->print();
 }
 class C:protected B
 {
 // friend void print2(C *c);
  
 };
 void print2(B *c)
 {
  A *a=c;
  cout<<"C()"<<endl;

 }

int main()
{

 B a,b;

   print2(&a);

 return 0;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值