如何理解C++中的继承与虚继承

发布时间:2021-09-24 17:26:22 作者:柒染
来源:亿速云 阅读:147

如何理解C++中的继承与虚继承,针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。

普通的公有继承

class test1
{
public:
    test1(int i) :num1(i) {}
private:
    int num1;
};
class test2 : public test1
{
public:
    test2(int i,int j) : test1(i), num2(j)
    {
    }
private:
    int num2;
};
void main()
{
    test2 t2(1,2);
}

(test2内存结构)查看内存发现父类在子类的上面

如何理解C++中的继承与虚继承

多重继承

在原有的代码基础上增加了test3类

test3类继承了 test2和test1

class test1
{
public:
    test1(int i) :num1(i) {}
private:
    int num1;
};
class test2
{
public:
    test2(int i) : num2(i)
    {
    }
private:
    int num2;
};
class test3 :public test2 ,public test1
{
public:
    test3(int i, int j,int k) :test1(i), test2(j),num3(k) {}
private:
    int num3;
};
void main()
{
    test3 t3(1, 2, 3);
}

(test3内存地址 ) 依旧是父类在子类上

但是现在有两个父类为什么test2在test1上?

这和我们的继承顺序有关 我们先继承了test2又继承了test1 更换内存继承顺序 内存的情况也会有所变化

如何理解C++中的继承与虚继承

虚继承

class test1
{
public:
    test1(int i) :num1(i) {}
private:
    int num1;
};
class test2: virtual public test1
{
public:
    test2(int i,int j) :test1(i), num2(j)
    {
    }
private:
    int num2;
};
void main()
{
    test2 t2(1, 2);
}

(t2的内存) 我们发现虚继承以后父类成员数据在子类成员数据下面了 首地址处莫名其妙多了四字节

这四字节就是我们的虚基类表的地址

如何理解C++中的继承与虚继承

跟随虚继承表 其中存储了本类距离父类对象的差值 通过差值能够找到父类对象

如何理解C++中的继承与虚继承

我们再看这个内存0x0082fbd8是t2的首地址 0x0082fbe0是父类的位置

0x0082fbd8 - 0x0082fbe0 == 8

就是本类距离父类对象的差值

如何理解C++中的继承与虚继承

虚继承(菱形继承)

class test1
{
public:
    test1(int i) :num1(i) {}
private:
    int num1;
};
class test2: virtual public test1
{
public:
    test2(int i,int j) :test1(i), num2(j)
    {
    }
private:
    int num2;
};
class test3 :virtual public test1
{
public:
    test3(int i, int j) :test1(i), num3(j){}
private:
    int num3;
};
class test4 :public test2, public test3
{
public:
    test4(int i, int j, int k) :test1(i),test2(i,j), test3(i,j),num4(k)
    {
    }
private:
    int num4;
};
void main()
{
    test4 t4(1, 2,3);
}


test4的内存 我们看到 t2和t3都有自己的虚基类表地址 记录了自己和父类的偏移

如何理解C++中的继承与虚继承

两个虚基类表的内容

现在我们计算一下 到爷爷类的差值是否正确

0x00FAFD50 - 0x00fafd3c == 14

0x00FAFD50 - 0x00fafd44 == C

如何理解C++中的继承与虚继承

关于如何理解C++中的继承与虚继承问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注亿速云行业资讯频道了解更多相关知识。

推荐阅读:
  1. C++多重继承中的虚继承和虚函数举例
  2. C++多重继承中的虚继承举例

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

c++

上一篇:如何在引擎BAE上搭建或迁移WordPress

下一篇:python中数据类型的示例分析

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》