1.概述

前面我们已经了解到c++内置了常用的数据类型,比如int、long、double等,但是如果我们要定义一个学生这样的数据类型,c++是没有的,此时就要用到结构体,换言之通过结构体可以帮我们定义自己的数据类型。

2.结构定义和使用

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

比如定义一个学生类型结构体

struct Student
{
string name;
int age;

};

上面定义好了学生这种数据类型,那如何创建一个Student类型的数据呢?有以下三种方式,推荐一二种

第一种

#include <iostream>
#include <string>
using namespace std;
struct Student
{
string name;
int age;

};
int main() {
//第一种,创建并赋值
Student s1;
s1.name = "张三";
s1.age = 12;
cout << s1.age << s1.name;
}

第二种

#include <iostream>
#include <string>
using namespace std;
struct Student
{
string name;
int age;

};
int main() {
//第二种
struct Student s1 = {"李四",12};

cout << s1.age << s1.name;
}

第三种

#include <iostream>
#include <string>
using namespace std;
struct Student
{
string name;
int age;

}s1;
int main() {
s1.age = 12;
s1.name = "lisi";
cout << s1.age << s1.name;
}

3.结构体数组

#include <iostream>
#include <string>
using namespace std;
//1.定义一个student结构体
struct student
{
string name;
int age;

};


int main() {
//2.定义结构体数组
struct student arr[3] =
{
{"aaa",12},
{"bbb",12},
{"ccc",12}
};
//3.结构体变量赋值
arr[2].age = 20;
arr[2].name = "ddd";
//4.访问结构体数组
for (int i = 0; i < 3; i++) {
cout << arr[i].age << arr[i].name <<endl;
}
}

4.结构体指针

#include <iostream>
#include <string>
using namespace std;
//1.定义一个student结构体
struct student
{
string name;
int age;

};


int main() {

struct student s = { "lisi",12 };
//2.定义一个结构体指针
struct student* p = &s;
//4.使用结构体指针访问结构体中的属性,需要使用->
cout << p->age << p->name;

}

5.嵌套结构体

#include <iostream>
#include <string>
using namespace std;
//1.定义一个student结构体
struct student
{
string name;
int id;
};
//2.定义一个嵌套结构体
struct school {
string name;
int id;
struct student s;
};
int main() {
//3.创建school变量
school sc = {};
sc.id = 1;
sc.name = "清华";
sc.s.id = 2;
sc.s.name = "lisi";
cout << sc.id << sc.name << sc.s.id << sc.s.name << endl;
}

6.结构体作为函数参数传递

第一种作为值传递(不会修改实参)

#include <iostream>
#include <string>
using namespace std;
//1.定义一个student结构体
struct student
{
string name;
int id;
};
void p(struct student s);
int main() {
struct student s = { "lisi",10 };
p(s);
cout << "id:" << s.id <<"姓名:"<< s.name<<endl;//id:10姓名:lisi
return 0;
}
//2.定义一个函数
void p(struct student s) {
s.id = 100;
cout << "id:" << s.id <<"姓名:" << s.name << endl;//id:100姓名:lisi
}

 

第二种作为地址传递(会修改实参)

#include <iostream>
#include <string>
using namespace std;
struct student
{
string name;
int id;
};
void p(struct student *s);
int main() {
struct student s = { "lisi",10 };
p(&s);
cout << "id:" << s.id <<"姓名:"<< s.name<<endl;//id:100姓名:lisi
return 0;
}
void p(struct student *s) {
s->id = 100;
cout << "id:" << s->id <<"姓名:" << s->name << endl;//id:100姓名:lisi
}

注意:

//使用地址传递可以避免大量变量赋值占用空间的问题,提高效率,但是会修改实参,如何解决?
void p(const struct student* s) {//使用const修饰之后,对于地址传递,只会读不会修改数据
//s->id = 100;将不能修改
cout << "id:" << s->id << "姓名:" << s->name << endl;//id:100姓名:lisi
}

 

有问题可以关注公众号:java一号