本文用于总结C++中结构体的各种使用方法!!!
#include <iostream>
using namespace std;
int main(int *argc, int **argv)
{
//1.定义结构体 结构体名称为Student
struct Student
{
char name[20];
int age;
};
struct Student stu1 = {"name",20};//声明结构体变量,并初始化
Student stu1 = {"name",20};//C++允许省略关键字struct
Student Class[2] = { {"name",20}, {"name",20} };//定义结构体数组,数组的每个元素为结构体,并初始化
Student *p = &stu1;//声明结构体指针变量
//2.同时完成定义结构体和创建结构变量
struct Student
{
char name[20];
int age;
}stu1,stu2;
//3.声明没有结构体名称的结构体,但只能在结构体定义时定义结构体变量
struct
{
char name[20];
int age;
}stu1;
stu1 = { "name", 20 };//结构体变量初始化
//4.类型定义结构体,为结构体名称定义别名
typedef struct Class
{
char name[20];
int age;
}Student, *p;//Student 等价于结构体名称Student,定义指针结构体别名
Student stu1 = { "name", 20 };//声明变量,并初始化
p point = &stu1;//声明指针结构体变量
cout << point->name << endl;
struct Class
{
char name[20];
int age;
};
typedef struct Class Student;//通过typedef struct 重新定义结构体名称,等价于以上定义
//5.结构体变量和结构指针变量所占内存
cout << "输出结构体变量所占内存大小: " <<sizeof(stu1) << endl;
cout << "输出指针结构体所占内存大小:"<<sizeof(point) << endl;
return 0;
}
参考资料:
1.《C++ Primer Plus》第六版