直接上图:

以及:

实践如下:

#include <iostream>
using namespace std;


class Father{

    private:
        int father1;
        int getFather1Private(){
            return this->father1;
        }

    protected:
        int father2;
        int getFather2Protected(){
            return this->father2;
        }
    public:
        int father3;
        Father(){
            this->father1 = 11;
            this->father2 = 10;
            this->father3 = 22;
            cout<< "无参构造器"<<endl;
        }
        // 基类构造器要加virtual的原因:
        // 这是因为当用基类引用派生类的时候,如果此时对基类进行delete操作,对于没有虚函数析构函数,那么只会调用基类的析构函数,而对派生类的析构函数不会进行析构
        virtual ~Father(){
            cout<< "Father析构函数"<<endl;
        }
        Father(int aa){
            this->father1 = aa;
            this->father2 = 10;
            this->father3 = 22;
            cout<< "有参构造器"<<endl;
        }
        int getFather1(){
            return father1;
        }
        int getFather2(){
            return father2;
        }
        int getFather3(){
            return this->father3;
        }
};

class Son : public Father{

    private:
        int son1;

    public:
        Son(){
            this->son1 = 11;
        }
        ~Son(){
            cout<< "Son析构函数"<<endl;
        }
        // 通过这样的方式调用父类构造器
        Son(int fatherV, int sonV):Father(fatherV){
             Father::father3 = fatherV;
            this->son1 = sonV;

        }
        int method(){
            int value = son1 * Father::father3;
            return value;
        }
        int getSon1(){
            return son1;
        }

};


int main(){

    cout << "类继承实践:" << endl;

    // 调用无参构造器
    Son son1;

    // 有参构造器
    Son son(121,222);

    // 在类外部仅有父类的public可以访问
        // error: cout << "son.getFather1Private():" << son.getFather1Private() << endl;
        // error: cout << "son.getFather2Protected():" << son.getFather2Protected() << endl;
    cout << "son.getFather1():" << son.getFather1() << endl;
    cout << "son.getFather2():" << son.getFather2() << endl;

    cout << "son.father3:" << son.father3 << endl;
    // error: cout << "son.father2:" << son.father2 << endl;

    cout << "son.getSon1():" << son.getSon1()<< endl;

    //cout << "son.father3:" << son.son1 << endl;
    cout << "son.method():" << son.method() << endl;


    // https://blog.csdn.net/u014453898/article/details/60402586
    // 这是因为当用基类引用派生类的时候,如果此时对基类进行delete操作,对于没有虚函数析构函数,那么只会调用基类的析构函数,而对派生类的析构函数不会进行析构
    Father *ptr = new Son();
    cout << "泛型:" << ptr->father3 << endl;
    delete ptr;

    cout << "类继承 实践 end." << endl;

    return 0;
}

 

posted on 2019-07-11 08:57  大辉_FFf  阅读(280)  评论(0编辑  收藏  举报