C++ 学习(虚基类)
来源:互联网 发布:医疗大数据公司排名 编辑:程序博客网 时间:2024/04/30 15:39
#include <iostream>//基类using namespace std;class CBase{protected: int a;public: CBase(int na) { a=na; cout<<"CBase constructor! "<<endl; } ~CBase(){cout<<"CBase deconstructor! "<<endl;}};//派生类1(声明CBase为虚基类)class CDerive1:virtual public CBase{public: CDerive1(int na):CBase(na) { cout<<"CDerive1 constructor! "<<endl; } ~CDerive1(){cout<<"CDerive1 deconstructor! "<<endl;} int GetA(){return a;}};//派生类2(声明CBase为虚基类)class CDerive2:virtual public CBase{public: CDerive2(int na):CBase(na) { cout<<"CDerive2 constructor! "<<endl; } ~CDerive2(){cout<<"CDerive2 deconstructor! "<<endl;} int GetA(){return a;}};//子派生类class CDerive12:public CDerive1,public CDerive2{public: CDerive12(int na1,int na2,int na3):CDerive1(na1),CDerive2(na2),CBase(na3) { cout<<"CDerive12 constructor! "<<endl; } ~CDerive12(){cout<<"CDerive12 deconstructor! "<<endl;}};int main(){ CDerive12 obj(100,200,300); //得到从CDerive1继承的值 cout<<" from CDerive1 : a = "<<obj.CDerive1::GetA(); //得到从CDerive2继承的值 cout<<" from CDerive2 : a = "<<obj.CDerive2::GetA()<<endl<<endl; return 0;}
参考: http://blog.chinaunix.net/uid-26983585-id-3309645.html
http://blog.csdn.net/livelylittlefish/article/details/2171267
http://blog.sina.com.cn/s/blog_4a286b4e010125rk.html
c++ 引入虚基类的原因是多继承产生了二义性。
虚基类的特点:
虚基类构造函数的参数必须由最新派生出来的类负责初始化(即使不是直接继承);
虚基类的构造函数先于非虚基类的构造函数执行
虚基类的构造函数先于非虚基类的构造函数执行
在类中,如果什么都没有,则类占用1个字节,一旦类中有其他的占用空间成员,则这1个字节就不在计算之内,如一个类只有一个int则占用4字节而不是5字节。如果只有成员函数,则还是只占用1个字节,因为类函数不占用空间。
虚函数因为存在一个虚函数表,需要4个字节,数据成员对象如果为指针则为4字节,注意有字节对齐,如果为13字节,则进位到16字节空间。
0 0
- [C学习]函数(?)
- C#(WINFORM)学习
- C学习(2)
- 学习资源(C++)
- C++&C学习笔记(一)(基础)
- Linux-GCC学习(C/C++)
- C指针学习(Pointers in C)
- 学习C语言的相关网站(C学习资料)
- 学习C语言的相关网站(C学习资料)
- 如何学习C++(经典)
- [C学习]总结(数据类型)
- ---------------C#(.NET)学习步骤---------
- C++test 学习(一)
- C++test 学习(二)
- C++test 学习(三)
- C++test 学习(四)
- C++test 学习(五)
- C#_WinForm学习(1)
- Linux Advance--线程和fork
- 1093. Count PAT's (25)
- 多线程 NSOperation
- Google Protocol Buffers介绍
- samba ubuntu下快速配置
- C++ 学习(虚基类)
- FindBugs插件的安装与使用
- SDWebImage 第三方框架
- 安卓学习知识点总结一
- 源码解析Volley框架
- LeetCode OJ ——Find Minimum in Rotated Sorted Array
- 运行循环
- [leetcode]Remove Element
- js 字符串转日期