CPP的类的访问方式与基础继承

访问方式与继承的特点:
1、类中的protected和private成员,类对象不可显示调用,子类的成员可以调用父类protected成员,但是不能调用private成员。
2、父类中的protected成员被子类以public方式继承后,化为protected成员。
3、父类中的protected成员被子类以protected方式继承后,化为private成员(不常用)。

继承方式的表格:

 基类的访问特性

 类的继承特性

 子类的访问特性

public

protected

private

public 

public

protected

NO access 

public

protected

private

proctected

protected

protected

NO access

public

protected

private

private

private

private

NO access


1、对象不可 显示调用protected成员和private成员。
class Animal
{
public:
    void eat()
    {cout<<"animal eat"<<endl;}
protected:
    void sleep()
    {cout<<"animal sleep"<<endl;}
private:
    void breathe()
    {cout<<"animal breathe"<<endl;}
};
int main()
{
    Animal an;
    an.eat();
    an.sleep();//外部不可以调用
    an.breathe();//外部不可以调用
    return 1;
}


2、子类的成员函数中可以调用父类的protected成员
class Animal
{
public:
    void eat()
    {cout<<"animal eat"<<endl;}
protected:
    void sleep()
    {cout<<"animal sleep"<<endl;}
private:
    void breathe()
    {cout<<"animal breathe"<<endl;}

};
class Fish: public Animal//派生类(子类):基类(父类) 注意继承方式为公有继承
{
 public:
      void test()
      {
          eat();
          sleep();//子类调用父类中的成员函数(可调用)
          breathe();//调用失败
      }
};
int main()
{
    Fish fh;
   fh.test();

    fh.eat();
    //fh.sleep();//protected外部不可调用
    //fh.breathe();//private外部不可调用
    return 1;
}


3、 构造函数释放顺序为:从父类到子类;析构函数释放顺序为:从子类到父类
class Animal
{
    public:
    Animal(int a,int b)
    {cout<<"animal construct"<<endl;}
    ~Animal()
    {cout<<"animal deconstruct"<<endl;}
    void eat()
     {cout<<"animal eat"<<endl;}
    void sleep()
     {cout<<"animal sleep"<<endl;}
     void breathe()
     {cout<<"animal breathe"<<endl;}
};

class Fish:public Animal
{
public:
      Fish():Animal(400,300),a(1)//XXX:向基类传递参数,对a初始化为1
      {cout<<"fish construct"<<endl;}
      ~Fish()
      {cout<<"fish deconstruct"<<endl;}
private:
       const int a;//对常量初始化
};

int main()
{
   Fish fh;
   return 1;
}

输出结果:
animal construct//构造函数释放顺序为:从父类到子类
fish construct
fish deconstruct//析构函数释放顺序为:从子类到父类
animal deconstruct


转载于:https://my.oschina.net/crooner/blog/147388

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值