https://github.com/zytc2009/BigTeam_learning
分类: C/C++
2010-09-25 10:15:05
类的内存布局-sizeof(类对象)
一、简单对象
#include
class A
{
public:
int a;
char b;
static int c;
virtual ~A(){};
};
int A::c=123;
int main()
{
A asimple;
cout<
} //result=4+4+1+3=12即字节对齐(虚指针+非静态数据成员)
二、单继承
#include
class A
{
public:
int a;
char b;
static int c;
virtual ~A(){};
};
int A::c=123;
class B:public A
{
public:
int d;
virtual void foob(){};
};
int main()
{
// A asimple;
B bsimple;
cout<
} //result=(4+4+1+3)+4=16即字节对齐(基类size+B自己的非静态数据成员)
三、多继承
#include
class A
{
public:
int a;
char b;
static int c;
virtual ~A(){};
};
int A::c=123;
class B
{
public:
int d;
virtual void foob(){};
};
class C:public A,public B
{
public:
int e;
};
int main()
{
A asimple;
B bsimple;
C csimple;
cout<
cout<
cout<
return 0;
}
四、菱形继承
1.非虚拟继承方式
#include
class A
{
public:
int a;
char b;
static int c;
virtual ~A(){};
virtual void fooa(){};
};
int A::c=123;
class B:public A
{
public:
int d;
virtual void foob(){};
};
class C:public A
{
public:
int e;
};
class D:public B,public C
{
public:
char f;
};
int main()
{
A asimple;
B bsimple;
C csimple;
D dsimple;
cout<
cout<
cout<
cout<
return 0;
}
2.虚拟继承
(1)B中重写fooa(),但不定义新的虚函数
#include
class A
{
public:
int a;
char b;
static int c;
virtual ~A(){};
virtual void fooa(){};
};
int A::c=123;
class B:virtual public A
{
public:
int d;
// virtual void foob(){};
virtual void fooa(){cout<<"fooa in B"<
class C:virtual public A
{
public:
int e;
};
class D:public B,public C
{
public:
char f;
};
int main()
{
A asimple;
B bsimple;
C csimple;
D dsimple;
cout<
cout<
cout<
return 0;
}
(2)B定义新的虚函数
#include
class A
{
public:
int a;
char b;
static int c;
virtual ~A(){};
virtual void fooa(){};
};
int A::c=123;
class B:virtual public A
{
public:
int d;
virtual void foob(){cout<<"foob in B"<
class C:virtual public A
{
public:
int e;
};
class D:public B,public C
{
public:
char f;
};
int main()
{
A asimple;
B bsimple;
C csimple;
D dsimple;
cout<
cout<
cout<
cout<
return 0;
}
综合1,2,可见
1.非虚拟继承时,无论派生类是否定义新的虚函数,基类和派生类总是共享一个虚函数表,不需要另加指向虚函数的指针。
2.虚拟继承时,若是派生类只是继承或重写基类中虚函数,则基类和派生类是共享一个虚函数表;若派生类新定义了虚函数,则需要新加一个虚指针指向新的虚函数表。