1. 程式人生 > >c++裡類的繼承

c++裡類的繼承

#include "stdafx.h"

#include<Windows.h>

#include<iostream>

using namespace std;

//繼承:程式碼複用

//父類的指標可以指向孩子的物件

//繼承過來的普通函式,如果建立物件的時候指標型別是什麼型別,那麼就執行什麼型別的函式

class CA

{

public:

        CA();

        ~CA();

        virtual void Print();

        //虛擬函式       

private:

};

CA::CA()

{

}

CA::~CA()

{

}

void CA::Print()

{

        cout << "A"<<endl;

}

class CB:public CA

{

public:

        CB();

        ~CB();

        void Print();

private:

};

CB::CB()

{

}

CB::~CB()

{

}

void CB::Print()

{

        cout << "B"<<endl;

}

int main()

{

        CA* pA1 = new CA;

        pA1->Print();//a

        CB* pB1= new CB;

        pB1->Print();

        pA1 = pB1;//b

        pA1->Print();//a

        //改為虛擬函式

        pA1 = pB1;//b

        pA1->Print();//b

        system("pause");

    return 0;

}