//深入理解一下继承以及虚函数的空间大小
#include <iostream>
using namespace std;
class A
{
char A[100];
};
class B:public A
{
char B[100];
};
class C:public A
{
char C[100];
};
class D:public B,public C
{
char D[100];
};
//对其它类的虚继承
class E:public virtual A
{
char E[100];
};
class F:public virtual B
{
char F[100];
};
//函数传参获取数组长度的方法
template<typename T,int N>
void printArrLength(T (&C)[N])
{
cout << "C[] spare mem space is " << sizeof(C) << endl;
cout << "C[] length is " << N << endl;
cout << "The array typebyte is " << sizeof(C)/N << endl;
}
/*
详细的讲解
虚继承:在继承定义中包含了virtual关键字的继承关系
虚基类:在虚函数体系中的,通过virtual继承而来的基类,需要注意的是:
class CSubClass:public virtual CBase {};
其中,CBase称为CSubClass的虚基类,而不是说CBase就是个虚基类
*/
struct CBaseClass1
{
CBaseClass1(size_t n):m_val(n) {}
public:
size_t m_val;
};
struct CSubClassV1:public virtual CBaseClass1
{
CSubClassV1(size_t n):CBaseClass1(n) {}
};
struct CSubClassV2:public virtual CBaseClass1
{
CSubClassV2(size_t n):CBaseClass1(n) {}
};
struct CDiamondClass1:public CSubClassV1,public CSubClassV2
{
CDiamondClass1(size_t n):CBaseClass1(n),CSubClassV1(n),CSubClassV2(n) {}
};
struct CDiamondSubClass1:public CDiamondClass1
{
CDiamondSubClass1(size_t n):CBaseClass1(n),CDiamondClass1(n) {}
};
//函数指针
void fa() { cout << "hello fa" << endl; }
void fb() { cout << "hello fb" << endl; }
void fc() { cout << "hello fc" << endl; }
//定义函数指针,返回类型为void,参数传递为void
typedef void (*funcptr)(void);
//在堆区产生二维数组
void new2DArray(int x,int y)
{
int ** p=new int*[y];
for(int i=0;i<y;i++)
p[i]=new int[x];
int count=0;
for(int i=0;i<x;i++)
for(int j=0;j<y;j++)
p[i][j]=count++;
for(int i=0;i<x;i++)
{
for(int j=0;j<y;j++)
cout << p[i][j] << " ";
cout << endl;
}
}
//测试部分
int main()
{
//直接继承时各个类所占空间的大小
cout << "sizeof(A) " << sizeof(A) << endl;//100
cout << "sizeof(B) " << sizeof(B) << endl;//200
cout << "sizeof(C) " << sizeof(C) << endl;//200
cout << "sizeof(D) " << sizeof(D) << endl;//500
//对于虚继承类函数的大小的空间,这里面还有虚函数的指针
cout << "sizeof(E) " << sizeof(E) << endl;//200+4
cout << "sizeof(F) " << sizeof(F) << endl;//300+4
//对于多继承中隐式转换的例子
D* pd = new D;
C* pc = dynamic_cast<C*>(pd);
B* pb = dynamic_cast<B*>(pd);
cout << (int)(void*)pc << endl;
cout << (int)(void*)pb << endl;
cout << (int)(void*)pc - (int)(void*)pb << endl;//200
//测试获取数组长度
int p[]={1,2,3,4,5};
printArrLength(p);
//函数指针的测试部分
funcptr fp;
char choosefunc;
cin >> choosefunc;
switch(choosefunc)
{
case ‘a‘:
fp=&fa;
break;
case ‘b‘:
fp=&fb;
break;
case ‘c‘:
fp=fc;
break;
default:
break;
}
//这里别忘了调用
(*fp)();
//测试二维数组的产生
new2DArray(4,5);
return 0;
}
原文地址:http://blog.csdn.net/berguiliu/article/details/44738531