类的继承与派生

继承:保持已有类的特性而构造新类的过程

派生:在已有类的基础上新增自己的特性而产生新类的过程

被继承的已有类称为基类(或父类)。
派生出的新类称为派生类。
 
作用:实现代码的重用
---------------------------------------------------------------------
继承方式:公有继承,私有继承,保护继承
公有继承:
基类的public和protected成员的访问属性在派生类中保持不变,但基类的private成员不可直接访问。(就是说在派生类中public和protected中同样保留有基类的public和protected的成员)
派生类成员函数:派生类中的成员函数可以直接访问基类中的public和protected成员,但不能直接访问基类的private成员。
派生类对象:通过派生类的对象只能访问基类的public成员。

#include<iostream>
using namespace std;
class A
{
public :
int x;
protected:
int y;
private:
int z;

};

class B:public A
{
public:
B()
{
x=3;
y=4;
}
void display()
{
cout<<x<<" "<<y<<" ";
}
};
int main()
{
B b1;
cout<< b1.x<<" ";
b1.display();


}

私有继承:

基类的public和protected成员都以private身份出现在派生类中,但基类的private成员不可直接访问。
--子类成员函数 可pulbic protected
--子类对象 不能直接调用父类任何成员

class A
            {
              public:
                int x;
              protected:
                int y;
              private:
                int z;                

            };

            class B : private  A
            {
                public:
                    void f(){};
                protected:
                    
                private:
                    //int x;
                    //int y;

            };
            int main()
            {
                 B b1;
                b1.
            }

保护继承:

基类的public和protected成员都以protected身份出现在派生类中,但基类的private成员不可直接访问。
--子类成员函数 可pulbic protected
--子类对象 不能直接调用父类任何成员

class A
            {
              public:
                int x;
              protected:
                int y;
              private:
                int z;                

            };

            class B : protected  A
            {
                public:
                    void f()
                    {
                        x
                        y
                    }
                protected:
                    // int x;
                    // int y;
                    
                private:
                    

            };
            int main()
            {
                 B b1;
                b1.
            }
 
原文地址:https://www.cnblogs.com/defen/p/5312961.html