c++ 中的继承

来源:互联网 发布:python class property 编辑:程序博客网 时间:2024/05/03 11:16
继承
 一个类从另一个类获取成员变量和成员函数的过程;
 被继承的类称为父类或者基类,继承的类称为子类或者派生类;
 继承的语法:
 class 派生类的名:[继承方式]  基类名{
  派生类的成员;
 };
  继承的方式:  public ,private,protect,默认是private;
   public成员可以通过对象访问,private只能通过内部函数访问;
  protected:也不能通过对象访问;
  继承的时候,protected成员可以在派生类中使用,基类的private不能在派生类中使用;
  
  继承的方式:
  1.public继承:
  基类中public成员在派生类中还是public属性;
  基类中protect成员在派生类中protected属性;
   .....private在派生类中不能使用;
   
   2.protected继承
    基类中public成员在派生类中为protected属性;
    .....protected.............protected.....;
    .....private在派生类中不能使用;
   3. private继承
   基类中public成员在派生类中为private属性;
   .....protected..............private....;
   .....private在派生类中不能使用;
     在派生类中访问基类的private成员的唯一方法就是借助基类的非private成员函数;
   如果没有这样的成员函数则无法访问;
     4, 改变访问权限 using
    使用using改变基类成员在派生类中的访问权限;
    public改成private, private改成public
    
    存在问题: 在派生类中无法访问基类中private成员,如何用using修改,编译的时候报错;

 

#include<iostream>
using namespace std;


//基类People
class People{
public:
    void show();
protected:
    char *m_name;
    int m_age;
};


void People::show(){
    cout<<m_name<<"的年龄是"<<m_age<<endl;
}


//派生类Student
class Student: public People{               
public:
    void learning();
public:
    using People::m_name;  //将private改为public
    using People::m_age;  //将private改为public
    float m_score;
private:
    using People::show;  //将public改为private
};
void Student::learning(){
    cout<<"我是"<<m_name<<",今年"<<m_age<<"岁,这次考了"<<m_score<<"分!"<<endl;
}


int main(){
    Student stu;
    stu.m_name = "小明";
    stu.m_age = 16;
    stu.m_score = 99.5f;
   // stu.show();  //compile error
    stu.learning();


    return 0;
}


0 0