继承对象模型

在c++编译器的内部类可以理解为结构体

子类是由父类成员叠加子类新成员得到的

继承对象模型的初探51-1:

#include <iostream>

#include <string>
using namespace std;
class demo
{
protected:
    int mi;
    int mj;
};
class derived:public demo
{
    int mk;
    public:
    derived(int i,int j,int k)
    {
        mi = i;
        mj = j;
        mk = k;
    }
    void print()
    {
        cout<<"mi = "<<mi << ","
            <<"mj = "<<mj << ","
            <<"mk = "<<mk << endl;
    }
};
struct Test
{
    int mi;
    int mj;
    int mk;
};
int main()
{
    cout<<"sizeof(demo) = "<<sizeof(demo)<<endl;
    cout<<"sizeof(derived) = "<<sizeof(derived)<<endl;
    derived d(1,2,3);
    Test* p = reinterpret_cast<Test*>(&d);
    cout<<"Before changing...."<<endl;
    d.print();
    p->mi = 10;
    p->mj = 20;
    p->mk = 30;
    cout<<"After changing...."<<endl;
    d.print();   
    return 0;
}

输出:

sizeof(demo) = 8
sizeof(derived) = 12
Before changing....
mi = 1,mj = 2,mk = 3
After changing....
mi = 10,mj = 20,mk = 30

多态对象模型

C++多态的实现原理

类中声明虚函数时,编译器会在类中生成一个虚函数表

虚函数表时一个存储成员函数地址的数据结构

虚函数表是由编译器自动生成与维护的

virtual成员函数会被编译器放入虚函数表中

存在虚函数时,每个对象中都有一个指向虚函数的指针

Slide6.PNG

调用虚函数存在三次寻址

#include <iostream>

#include <string>
using namespace std;
class demo
{
protected:
    int mi;
    int mj;
    virtual  void print()
    {
        cout<<"mi = "<<mi << ","
            <<"mj = "<<mj <<  endl;
    }
};
class derived:public demo
{
    int mk;
    public:
    derived(int i,int j,int k)
    {
        mi = i;
        mj = j;
        mk = k;
    }
    void print()
    {
        cout<<"mi = "<<mi << ","
            <<"mj = "<<mj << ","
            <<"mk = "<<mk << endl;
    }
};
struct Test
{
    void* p;
    int mi;
    int mj;
    int mk;
};
int main()
{
    cout<<"sizeof(demo) = "<<sizeof(demo)<<endl;
    cout<<"sizeof(derived) = "<<sizeof(derived)<<endl;
    derived d(1,2,3);
    Test* p = reinterpret_cast<Test*>(&d);
    cout<<"Before changing...."<<endl;
    d.print();
    p->mi = 10;
    p->mj = 20;
    p->mk = 30;
    cout<<"After changing...."<<endl;
    d.print();   
    return 0;
}

输出:

sizeof(demo) = 12
sizeof(derived) = 16
Before changing....
mi = 1,mj = 2,mk = 3
After changing....
mi = 10,mj = 20,mk = 30

小结:

继承的本质就是父子间成员变量的叠加

C++中的多态是通过虚函数表实现的

虚函数是由编译器自动生成与维护的

虚函数的效用效率低于普通成员函数


YingLi
6 声望4 粉丝

From zero to hero.