类对象存储方式
0 针对这个问题,你怎么解决?
class Student
{
private:
// 成员变量
char _name[20];
char _gender[3];
int _age;
public:
// 成员函数
void InitStudent(char name[], char gender[], int age)
{
strcpy(_name, name);
strcpy(_gender, gender);
_age = age;
}
// 注意:成员函数如果在类内部类进行定义,成员函数可能会被编译器当成内联函数来对待
void PrintStudent()
{
cout << _name << "-" << _gender << "-" << _age << endl;
}
void SetAge(int age)
{
_age = age;
}
};
int main()
{
Student s1, s2,s3;
s1.InitStudent("Peter", "男", 18);
s2.InitStudent("David", "男", 20);
s3.InitStudent("Lucy", "女", 19);
s1.PrintStudent();
s2.PrintStudent();
s3.PrintStudent();
return 0;
}
1 类对象的存储方式
1.1 类对象模型
要想谈类对象的存储方式,需先对类对象模型概念进行理解。
类对象模型—>对象在内存中的布局方式。其在对象中存储。
1.2 如何计算类对象的大小??
#if 0
// 如何计算一个类/对象的大小?
// 如果我们知道对象中都包含哪些内容
class Student
{
public:
// 成员变量
char _name[20];
char _gender[3];
int _age;
public:
// 成员函数
void InitStudent(char name[], char gender[], int age)
{
strcpy(_name, name);
strcpy(_gender, gender);
_age = age;
}
void PrintStudent()
{
cout << _name << "-" << _gender << "-" << _age << endl;
}
void SetAge(int age)
{
_age = age;
}
};
int main()
{
Student s1,s2,s3;
s1.InitStudent("Peter", "男", 18);
s2.InitStudent("David", "男", 19);
s3.InitStudent("Lily", "女", 18);
s1.PrintStudent();
s2.PrintStudent();
s3.PrintStudent();
cout << sizeof(s1) << endl;
return 0;
}
#endif
1.2.1 第一种方式:对象中包含类的各个成员
1.2.2 第二种方式:只保存成员变量,成员函数存放在公共代码段
1.2.3 第三种方式:对象中值存储成员变量,实际是sizeof的结果
!在这里插入代码片
在这里插入图片描述
1.2.4 空类的大小
#if 0
class A
{
public:
void SetA(int a)
{
_a = a;
}
private:
int _a;
};
class B
{
public:
void TestB()
{}
};
class C
{};
int main()
{
// 结论:求一个类的大小--->只需将类中"成员变量"加起来,注意内存对齐
cout << sizeof(A) << endl; // 4
cout << sizeof(B) << endl; // 1
cout << sizeof(C) << endl; // 1
}
#endif
主流编译器中,空类为1个字节,某些编译器是四个字节。空类为什么是1个字节??其实就是为了区分不同对象的。
1.2.5 空的结构体大小
// 分析:在C++中,用struct定义出来的结构体就是类
// 空类
#if 0
struct D
{};
int main()
{
cout << sizeof(D) << endl;
}
#endif
结论:在主流编译器中,依旧为1
往期链接:
cpp_6.1类与对象上(一)—类的引入
cpp_6 nullptr
cpp_5.2 auto关键字
cpp_5.1 内联函数
cpp_5 const修饰的变量和宏
cpp_4 引用
cpp_3 函数重载/传址调用/引用
cpp_2 输入输出/函数/重载
cpp_1 命名空间/输入输出