c++里类的继承

版权声明:虽然都是基础,但都是开源的,哈哈。 https://blog.csdn.net/qq_41490433/article/details/84345869

#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;

}

猜你喜欢

转载自blog.csdn.net/qq_41490433/article/details/84345869
今日推荐