C++ 结构体

231 阅读1分钟

1. 概念:结构体是用户自定义的数据类型,允许用户存储不同的数据类型

 

1.1 定义:

struct 结构体名 { 结构体成员列表 };

1.2 使用

通过结构体创建变量有3种方式

struct 结构体名 变量名

struct 结构体名 变量名 = { 成员值1, 成员值2...}

定义结构体时顺便创建

1.3 示例

struct Student

{

    string name;

    int age;

    int score;

};

 

//创建结构体变量,然后给成员列表赋值

    Student s1;

    s1.name = "张三";

    s1.age = 10;

s1.score = 99;

 

//创建结构体变量时,赋值

Student s2 = { "李四", 20, 10 };

 

//定义结构体时,创建结构体变量

struct Student

{

    string name;

    int age;

    int score;

}s3;

 

    s3.name = "张三";

    s3.age = 10;

s3.score = 99;

 

2. 结构体数组:将自定义的结构体放入数组中方便维护

Struct 结构体名 数组名[元素个数] = { 结构体变量1, 结构体变量2, ... }

 

3. 结构体指针:利用->可以通过结构体指针访问结构体内的成员

Student s2 = { "张三", 10, 20 };

    Student* s1;

    s1 = &s2;

    s1->age = 30;

s1->name = "李四";

s1->score = 99;

 

4. 结构体嵌套结构体

struct Student

{

    string name;

    int age;

    int score;

};

 

struct Teacher

{

    string name;

    int age;

    Student s[10];

};

 

5. 结构体作为函数的参数

void printStudent1(Student s)

{

    cout << "姓名="<<s.name<<" 年龄=" << s.age<<" 分数=" << s.score << endl;

}

 

void printStudent2(Student* s)

{

    cout << "姓名=" << s->name << " 年龄=" << s->age << " 分数=" << s->score << endl;

}

 

Student s = { "小王", 20, 30 };

printStudent1(s);

printStudent2(&s);

 

6. 结构体中的const

void printStudent2(const Student* s)

{

    s->age = 99;//错误

    cout << "姓名=" << s->name << " 年龄=" << s->age << " 分数=" << s->score << endl;

}