先演示一段代码:
#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;
}
运行结果

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

被折叠的 条评论
为什么被折叠?



