类对象的存储方式猜测

先演示一段代码:

#include<iostream>
using namespace std;
#pragma warning( disable : 4996)
#include<string.h>
class student {
public:
	void SetStudentInfo(char* name, char* gender, int age)
	{
		strcpy(_name, name);
		strcpy(_gender, gender);
		_age = age;

	}
	void SetStudentPrintf()
	{
		cout <<"姓名:" <<_name << "	性别:" << _gender << "		年龄:" << _age << endl;
		cout << endl;
	}
private:
	char _name[20];
	char _gender[3];
	int _age;
};

int main()
{
	s1.SetStudentInfo("hua", "nan", 3);
	s2.SetStudentInfo("2018", "ha", 2);
	s1.SetStudentPrintf();
	s2.SetStudentPrintf();

	system("pause");
	return 0;
}

*对象中包含的各个成员

缺陷:每个对象中成员变量是不同的,但是调用同一份函数,如果按照此种方式存储,当一个类创建多 个对象时,每个对象中都会保存一份代码,相同代码保存多次,浪费空间。那么如何解决呢?

***只保存成员变量,成员函数存放在公共的代码段

   问题:对于上述两种存储方式,那计算机到底是按照那种方式来存储的?
   我们再通过对下面的不同对象分别获取大小来分析看下

// 类中既有成员变量,又有成员函数
class A1
{
public:
	void f1()
	{}
private:
	int _a;
};

// 类中仅有成员函数 
class A2
{
public:
	void f2() {}
};

// 类中什么都没有---空类
class A3
{ };
int main()
{
	cout << sizeof(A1) << endl;
	cout << sizeof(A2) << endl;
	cout << sizeof(A3) << endl;

}

运行结果


 

结论:一个类的大小,实际就是该类中”成员变量”之和,当然也要进行内存对齐,注意空类的大小,空类比 较特殊,编译器给了空类一个字节来唯一标识这个类。
 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值