虚基类和虚继承
来源:互联网 发布:界面编程语言 编辑:程序博客网 时间:2024/06/05 02:01
这算得上我个人的一个总结上,其实也算不上什么原创,只是为了过滤一下前辈的经验,加深一下自己的记忆
虚继承的目的是让某个类做出声明,承诺愿意共享它的基类,被共享的那个基类就是虚基类
#include<iostream>using namespace std;class A{public:A(){}protected:int _a;};class B:public A{public:B(){}protected:int _b;};class C:public A{public:C(){} protected: int _c;};class D:public B,public C{public:D(){}void set_a(int a){ _a = a;}void set_b(int b){ _b = b;}void set_c(int c){ _c = c;}void set_d(int d){ _d = d;}protected:int _d;};int main(){D d;return 0;}当继承关系呈菱形继承的时候,由于最后一个派生类继承了两个拥有相同基类的派生类,相同派生类中继承的成员变量和成员函数发生冲突,这个时候就要用到虚继承,让派生类能够共享一样的基类。
#include<iostream>using namespace std;class A{public:A(){}protected:int _a;};class B:virtual public A{public:B(){}protected:int _b;};class C:virtual public A{public:C(){} protected: int _c;};class D:public B,public C{public:D(){}void set_a(int a){ _a = a;}void set_b(int b){ _b = b;}void set_c(int c){ _c = c;}void set_d(int d){ _d = d;}protected:int _d;};int main(){D d;return 0;}像这样在公有继承前面加上virtual就可以实现虚继承
阅读全文
1 0
- 虚继承和虚基类
- 虚继承和虚基类
- 虚继承和虚基类
- 虚基类和虚继承
- 虚继承和虚基类本质
- C++虚继承和虚基类
- 多重继承、钻石继承和虚继承
- 多重继承,钻石继承和虚继承
- 多重继承和虚继承
- 多重继承和虚继承
- 钻石继承和虚继承
- 菱形继承和虚继承
- 菱形继承和虚继承
- C++ 菱形继承问题 虚继承和虚基类
- 多继承的二义性和虚继承(虚基类)
- 虚继承和虚基类的本质
- 虚基类和虚继承的本质
- 虚继承和虚基类的本质
- 常用对象
- ubuntu16.04配置opencv 实现人脸识别
- [codeforces570D]Tree Requests(dsu on the tree)
- Mac环境svn的使用
- 科普 | 以链接为中心的系统:Link-based Systems
- 虚基类和虚继承
- 2.1 Spring5 快速入门
- POJ 2932 Coneology 笔记
- Linux 安装zabbix客户端
- This Activity already has an action bar supplied by the window decor
- 【LeetCode】C# 12、Integer to Roman
- 使用夹逼准则求解二重极限的例题(1)
- LEETheme优雅的主题管理库
- HTML中跳转到文章的指定段落