虚拟继承和虚基类
来源:互联网 发布:淘宝试用成功要付费吗 编辑:程序博客网 时间:2024/05/21 10:05
#include <iostream>using namespace std;class A{public: A() { cout<< "this is A constructor"<<endl; } //needly virtual ~A() { cout<<"this is A destructor"<<endl; } void Speak() { cout<<"this is A speak"<<endl; }};class B1 : public virtual A{public: B1() { cout<<"this is B1 constructor"<<endl; } ~B1() { cout<<"this is B1 destructor"<<endl; }};class B2 : public virtual A{public: B2() { cout<<"this is B2 constructor"<<endl; } ~B2() { cout<<"this is B2 destructor"<<endl; }};class C: public B1,public B2{public: C() { cout<<"this is C constructor"<<endl; } ~C() { cout<<"this is C destructor"<<endl; }};int main(){ C *p = new C(); p->Speak(); delete p; p = NULL; return 0;}
执行结果:
this is A constructor
this is B1 constructor
this is B2 constructor
this is C constructor
this is A speak
this is C destructor
this is B2 destructor
this is B1 destructor
this is A destructor
虚拟继承即在继承时再基类前面加一个virtual关键字,而虚基类便是A。
通过虚继承我们可以解决三个问题:
存储问题:因为当非虚继承时,类C的内存中,将会产生两份类A的拷贝。
效率问题:非虚继承时,基类的构造(析构)函数被调用两次。
编译问题:调用基类的成员函数时会产生二义性,如这里的Speak(),当非虚继承时,B1跟B2均会继承A的Speak()成员函数,那么当子类C调用时将产生二义性,虽然可用::指定,但这不符合设计原则跟开发原则。
0 0
- 虚拟继承和虚基类
- 虚拟函数和虚拟继承
- 多重继承和虚拟继承
- 虚拟继承和模板继承
- C++之虚拟继承和虚基类
- 虚拟继承,虚基类
- 虚拟继承,虚基类
- 虚拟继承,虚基类
- c++-虚拟继承、虚基类
- 虚拟继承、虚基类
- 虚拟继承与虚基类
- 虚基类与虚拟继承
- 虚拟继承和虚表
- 继承----有关虚函数和虚拟继承
- 关于虚拟继承和直接继承
- 关于多重继承和虚拟继承
- C++:菱形继承和虚拟继承
- 菱形继承和菱形虚拟继承探索
- 最新:2015年申报高新技术企业须满足的条件
- Highcharts JS去除Highcharts.com链接和print按钮
- LeetCode:Edit Distance
- String.format
- Android系统编译之增加和删除第三方应用
- 虚拟继承和虚基类
- 使用CCriticalSection类的注意事项
- 时间类(增加n)
- 写论文“四戒”:戒杂、戒浅、戒乱、戒错——再谈科技论文写作
- 第2章-uboot for smart210读取内核的ecc问题完美解决
- 一分钟倒计时
- 时间复杂度为O(m*n)最长公共子串
- StringBuilder.append 中出现加号影响效率
- 【数据结构课程作业】单链表逆置