C++——多态实现原理分析

前言

虚函数执行速度要稍慢一些。为了实现多态性,每一个派生类中均要保存相应虚函数的入口地址表,函数的调用机制也是间接实现。所以多态性总是要付出一定代价,但通用性是一个更高的目标。

实验环境

Windows10 企业版

Visual Studio2017 15.8.1

#include<iostream>
using namespace std;

class Base
{
public:
    Base()
    {
        cout << "Create Base" << endl;
    }
     ~Base()
    {
        cout << "Free Base" << endl;
    }
public:
    void Show()
    {
        cout << "This is Base Show()" << endl;
    }
private:
    int x;
};

void main()
{
    cout << sizeof(Base) << endl;
}
View Code

#include<iostream>
using namespace std;

class Base
{
public:
    Base()
    {
        cout << "Create Base" << endl;
    }
     ~Base()
    {
        cout << "Free Base" << endl;
    }
public:
    virtual void Show()
    {
        cout << "This is Base Show()" << endl;
    }
private:
    int x;
};

void main()
{
    cout << sizeof(Base) << endl;
}
View Code

猜你喜欢

转载自www.cnblogs.com/kelamoyujuzhen/p/9551717.html