三种继承方式的区别与联系

#include<iostream>
using namespace std;

class Base
{
public:
    void fun_1(){}
protected:
    void fun_2(){}
private:
    int x_;
};
class Derived :private Base
{
public:
    void fun_3()
    {
        fun_1();//私有继承过来变为自己的私有成员,在类内可以访问
        fun_2();
    }
protected:
    void fun_4();
private:
    int y_;
};
class TT:private Derived
{
    void fun5()
    {
        //fun_1();//fun_1已经转变为了Derived的私有成员,无论怎么继承后面无法访问。
    }
};
class Widget:public Base
{
    void fun()
    {
        //z_=x_;x_是Base的私有成员,即使在类内也无法访问
        fun_2();//fun_2通过两层继承还是Widget的protected成员,在类内可以访问
        /*protected和private成员的区别与联系:protected和private成员在类外均无法访问,通过对象只能访问public成员
          在类内自己的protected和private成员均可访问,那么区别在哪呢?就是当有继承产生的时候(不管何种继承方式),父类的private成员在
          子类类内是无法访问的,但是protected是在子类类内是可以访问的。
        */
    }
private:
    int z_;
};


class Person
{
public :
    virtual void print()
    {
        cout<<"Person"<<endl;
    }
};
class Student:public Person
{
public:
    void print()
    {
        cout<<"Student"<<endl;
    }
};

void MyPrint(Person& p)
{
    p.print();
}

int main()
{
    //运行时多态练习
    Person p;
    Student S;
    cout<<sizeof(p)<<endl;
    cout<<sizeof(S)<<endl;
    MyPrint(S);
    MyPrint(p);

    //继承练习
    Derived d;
    d.fun_3();
    //d.fun_2();fun_2是Base的protected成员,通过公有继承过来之后也是protected,通过对象无法访问
    //d.fun_4();fun_4是Derived的protected成员,外部无法访问
    return 0;
}

总而言之:

私有继承时基类中各成员属性均变为private,并且基类中private成员被隐藏。派生类的成员也只能访问基类中的public/protected成员,
而不能访问private成员;派生类的对象不能访问基类中的任何的成员。
保护继承时基类中各成员属性均变为protected,并且基类中private成员被隐藏。派生类的成员只能访问基类中的public/protected成员,
而不能访问private成员;派生类的对象不能访问基类中的任何的成员。 
 

猜你喜欢

转载自blog.csdn.net/crazy_to_imagine/article/details/81389411