c++ 每个类都有一张虚方法表

#include <iostream>

using namespace std;
/* 每个类都有一张虚方法表,当基类为虚方法,而派生类重载了虚方法,
* 则虚方法表中的基类方法被派生类替换
*/
class AClass{
    public:
        AClass(){
            cout << this << " 基类构造" << endl;
        }
        virtual ~AClass(){
            cout << this << " 基类析构" << endl;
        }
        void Amothod1(){
            cout << "基类方法1" << endl;}
        virtual void Amothod2(){
            cout << "基类方法2" << endl;}
        void Amothod3(){
            cout << "基类方法3" << endl;}
};
class BClass:public AClass{
    public:
        BClass(){
            cout << this << " 派生类构造" << endl;
        }
        virtual ~BClass(){
            cout << this << " 派生类析构" << endl;
        }
        void Amothod1(){
            cout << "派生类方法1" << endl;}
        void Amothod2(){
            cout << "派生类方法2" << endl;}
};

int main()
{
    AClass * a = new AClass;// 基类指针操纵基类实例
    a->Amothod1();// 调用基类方法1
    a->Amothod2();// 调用基类方法2
    a->Amothod3();// 调用基类方法3
    delete a;
    cout << "***虚方法不影响指向基类实例的基类指针***" << endl;

    AClass * a1 = new BClass;// 基类指针操纵派生类实例
    a1->Amothod1();// 调用基类方法1
    a1->Amothod2();// 调用派生类方法2
    a1->Amothod3();// 调用基类方法3
//    ((BClass *)a1)->Amothod1();// 等效于b->Amothod1();
//    ((BClass *)a1)->Amothod2();// 等效于b->Amothod2();
//    ((BClass *)a1)->Amothod3();// 等效于b->Amothod3();
    delete a1;
    cout << "***虚方法影响指向派生类实例基类指针***" << endl;

    BClass * b = new BClass;// 派生类指针操纵派生类实例
    b->Amothod1();// 调用派生类方法1
    b->Amothod2();// 调用派生类方法2
    b->Amothod3();// 调用基类方法3
//    ((AClass *)b)->Amothod1();// 等效于a1->Amothod1();
//    ((AClass *)b)->Amothod2();// 等效于a1->Amothod2();
//    ((AClass *)b)->Amothod3();// 等效于a1->Amothod3();
    delete b;
    cout << "***如果不重载基类公共方法,将直接调用基类方法***" << endl;

    return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值