结构体类型——内存分配

   几种常见的运算符的sizeof操作

   32位c++中的基本数据类型,就char,short/int(short),int,long/int(long) ,float,double,long double;

   其大小分别是1,2,4,4,4,8,10.

   在存储过程中,为了提高CPU的存储速度,编译器会对变量的起始地址做“对齐”处理。

   结构体的起始位置就是结构体中第一个变量所在位置。

   VC规定结构体的各变量存放的起始地址相对于结构体的起始地址的偏移量必须是该变量的类型所占字节数的倍数,并且整个结构体的字节数必须是该结构体中占用空间最大的类型的字节数的整数倍

  结构体的内存为:最后一个成员的便宜地址+最后一个成员的字节长度+最后一个成员的调整参数!

  过程:找出结构体变量相对于起始位置的偏移量,判断是否是该变量的倍数关系,不是的话补齐,以此类推到最后,到最后一个变量的偏移量,加上最后一个字节长度,后判断是否是结构体中最长的类型的倍数,若不是,补齐。

   

(1)先是定义了如下结构体:
     struct{
            char a; 相对于结构体起始位置的偏移量为0,char类型所占字节数为1,是倍数关系。
            int i;相对于结构体起始位置的偏移量是1,int所占字节数为4,不是倍数关系,补齐偏移量变为4,
           double d;那么d的偏移量为8, 8+8=16,16是4的倍数!
            }text;
   然后用sizeof(text),预期结果是1+2+8 = 11???如果这样想就错了,答案是16. 
(2)然后,换一下变量的顺序:
     struct{
            char a;0
            double d;1,1+7=8;
            int i;16,16+4=20,不是8的倍数,所以+4,变为24
           }text;
   猜猜答案是多少?11?16?错,答案是24
(3)再换个顺序:
     struct{
            double d; 0
            char a;8,
            int i;8+1+4=13  不是8的倍数,+3,变为16
            }text;
   又开始猜答案了,11?16?24?这次终于蒙对了,答案是16

  一个早上终于弄懂了。。。


class类

#include <iostream>
#include <string>
#include <vector>

class test
{
public:
	test();
	virtual ~test();
	virtual void get_a_c();
private:
	int a;
	char c;
};

class derived_test :public test
{
public:
	virtual ~derived_test();
private:
	double d;
};

class base
{
private:
	char a;
	static int refrence_count;
	std::string name;
	double price;
	std::vector<double> dvec;
public:
	base();
	virtual ~base();
	static int get_count();
};

int base::get_count()
{
	return refrence_count;
}

int base::refrence_count = 0;

class new_base
{
private:
	char a;
	double price;
	std::vector<double> dvec;
	std::string name;
	static int refrence_count;
public:
	new_base();
	virtual ~new_base();
	static int get_count();
};

int new_base::get_count()
{
	return refrence_count;
}
int new_base::refrence_count = 0;

class derived : public base
{
private:
	int min_qty;
	double discount;
	static int newp;
public:
	derived();
	virtual ~derived(){};
};

class new_derived :public new_base
{
private:
	double discount;
	int min_pty;
	static int newp;
public:
	new_derived();
	virtual ~new_derived(){}
};

int main()
{
	int a = sizeof(test);
	std::cout << "The size of test is " << a << std::endl;
	std::cout << "The size of derived_test is " << sizeof(derived_test) << std::endl;
	std::cout << "The size of base is " << sizeof(base) << std::endl;
	std::cout << "The size of new_base is " << sizeof(new_base) << std::endl;
	std::cout << "The size of derived is " << sizeof(derived) << std::endl;
	std::cout << "The size of new_derived is " << sizeof(new_derived) << std::endl;

	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值