c++虚函数及static的内存分配情况

来源:互联网 发布:中国宇航出版社 知乎 编辑:程序博客网 时间:2024/06/18 13:47

class gfather
{
public:
void a() { cout << “gfather a();\n”; }
void b() { cout << “gfather b();\n”; }
void c() { cout << “gfather c();\n”; }
};
//C++调用虚函数的时候,要根据实例(即this指针指向的实例)中虚函数表指针得到虚函数表,再从虚函数表中找到函数的地址。
//没有virtual关键字,sizeof(father)占用1字节,有virtual关键字,sizeof(father)占用4字节,因为包含了虚函数指针
class father
{
public:
void a() { cout << “father a();\n”; }
virtual void b() { cout << “father b();\n”; }
void c() { cout << “father c();\n”; }
};

class mother
{
public:
void i() { cout << “father a();\n”; }
virtual void j() { cout << “father b();\n”; }
virtual void k() { cout << “father c();\n”; }
};

class son : public father, public mother //包含了他们的虚函数指针
{
public:
void b() { cout << “son b()\n”; }
void j() { cout << “son j()\n”; }
};

class sson :public father, public mother
{
public:
virtual void x() { cout << “sson x()\n”; }
void c() { cout << “sson c()\n”; }
};

class cA
{
int a;
int b;
public:
void A() {}
};
class cB
{
int a;
int b;
static int c; //不属于哪个对象,因此不会分配内存
public:
void B() {}
};
struct stA
{
int a;
int b;
public:
void A() {}
};
struct stB
{
int a;
int b;
static int c;
public:
void B() {}
};
struct stC //空结构体
{
//空的结构体和空的类,操作系统只分配1个字节空间
};
int cB::c = 0;
int stB::c = 0;
int main()
{
cout << sizeof(son) << endl; //8
cout << sizeof(father) << endl; //4
cout << sizeof(mother) << endl; //4
cout << sizeof(gfather) << endl; //1
cout << sizeof(sson) << endl; //8
cout << sizeof(cA) << endl; //8
cout << sizeof(cB) << endl; //8
cout << sizeof(stA) << endl; //8
cout << sizeof(stB) << endl; //8
cout << sizeof(stC) << endl; //1
return 0;
}

0 0