//本机为64位的环境
类的普通成员函数是不占用字节的,有虚函数时,需要指向虚函数表的指针(所以跟有几个虚函数无关)和成员变量占用字节(静态成员变量不占用)。
cpp文件代码如下:
#include "class_size_attr.h"
Father father;
Son son;
int main(int argc ,char*argv[])
{
Empty empty;
printf("sizeof empty class is %d\n",sizeof(empty));
printf("sizeof father class is %d\n",sizeof(father));
printf("sizeof son class is %d\n",sizeof(son));
}1、空类的长度为1 :为了实现每个实例在内存中都有一个独一无二的地址,编译器往往会给一个空类隐含的加一个字节,这样空类在实例化后在内存得到了独一无二的地址,所以空类所占的内存大小是1个字节
2、父类,子类只包含一个char 数据成员
#include <stdio.h>
#include <stdlib.h>
class Empty{
};
class Father{
private:
char char_num;
public :
Father()
{
printf("Father()\n");
}
~Father()
{
printf("~Father()\n");
}
};
class Son:public Father
{
private:
char char_num;
public:
Son()
{
printf("Son()\n");
}
~Son()
{
printf("~Son()\n");
}
};
运行结果:
3.各只有一个int 数据成员:
4.各有一个int 和char 成员
5。一个int char 以及虚函数 以及注意使用父类的指针指向之类对象,调用的虚函数为子类对象的
头文件:
#include <stdio.h>
#include <stdlib.h>
class Father{
private:
int int_num;
char char_num;
public :
virtual void fun();
};
class Son:public Father
{
private:
int int_num;
char char_num;
public:
virtual void fun();
};
void Father::fun()
{
printf("Father fun()\n");
}
void Son:: fun()
{
printf("Son fun()\n");
}cpp文件:
#include "class_size_attr.h"
Father father;
Son son;
int main(int argc ,char*argv[])
{
Father *pfather = &son;
printf("sizeof father class is %d\n",sizeof(father));
printf("sizeof son class is %d\n",sizeof(son));
pfather->fun();
}运行结果: 如果子类没有复写父类的虚函数,则调用的为父类的虚函数
7。分别只有一个int 和虚函数和只有一个char 和虚函数的结果是一样的
8.只有一个虚函数的长度(寻址长度)
版权声明:本文为istone218原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。