结构体:结构体属于用户自定义的数据类型,允许用户存储不同的数据类型
结构体的定义和使用
语法:struct 结构体名 {结构体成员列表};
通过结构体创建变量的三种方式:
1.struct 结构体名 变量名
#include <iostream>
using namespace std;
struct Student {
string name;
int age;
};
int main() {
struct Student s1;
s1.name = "张三";//对结构体中的成员赋值
s1.age = 20;
system("pause");
return 0;
}
2.struct 结构体名 变量名 = {成员1值, 成员2值}
#include <iostream>
using namespace std;
struct Student {
string name;
int age;
};
int main() {
struct Student s1 = {"张三",20};
system("pause");
return 0;
}
3.定义结构体时顺便创建变量
#include <iostream>
using namespace std;
struct Student {
string name;
int age;
}s1;
int main() {
s1.name = "张三";
s1.age = 20;
system("pause");
return 0;
}
创建结构体变量,可以将struct省略去
结构体数组
将自定义的结构体放入数组中方便维护
#include <iostream>
using namespace std;
struct Student {
string name;
int age;
}s1;
int main() {
struct Student s1[2] = {
{"张三",20},
{"李四",30}
};
system("pause");
return 0;
}
结构体指针
作用:通过指针访问结构体中的成员
利用操作符 ->可以通过结构体指针访问结构体的属性
#include <iostream>
using namespace std;
struct Student {
string name;
int age;
}s1;
int main() {
struct Student s1[2] = {
{"张三",20},
{"李四",30}
};
Student* p = s1;
cout<<"姓名是:"<<p->name<<"年龄是:" <<p->age<< endl;
cout << "姓名是:" << p++->name << "年龄是:" << p->age << endl;
system("pause");
return 0;
}
结构体嵌套结构体
作用:结构体中的成员可以是另一个结构体
#include <iostream>
using namespace std;
struct Student {
string name;
int age;
};
struct Teacher {
int number;
string name;
struct Student stu;
};
int main() {
Teacher t;
t.name = "老师";
t.number = 123456;
t.stu.name = "张三";
t.stu.age = 20;
system("pause");
return 0;
}
结构体做函数参数
作用:将结构体作为参数向函数中传递
#include <iostream>
using namespace std;
struct Student {
string name;
int age;
};
//1.值传递
void printStudent1(Student stu) {
cout<<stu.name<<" " << stu.age << endl;
}
//2.地址传递
void printStudent2(Student* stu) {
cout << stu->name<<" " << stu->age << endl;
}
int main() {
Student s;
s.name = "张三";
s.age = 20;
printStudent1(s);
printStudent2(&s);
system("pause");
return 0;
}
结构体中const使用场景
作用:用const来防止误操作
原因:因为在面对大量的数据时,使用值传递会在内存中存在数值的拷贝,这个运用的内存就会增多,但是指针类型的内存是恒定的,所以这个时候适合用指针进行操作,但是用指针修改数据会造成所有的数据都会修改,因此使用const来限制数据被修改。
#include <iostream>
using namespace std;
struct Student {
string name;
int age;
};
void printStudent(const Student* stu) {
//stu->age = 100;//因为运用了const,所以这里的修改将无效
cout << stu->name<<" " << stu->age << endl;
}
int main() {
Student s;
s.name = "张三";
s.age = 20;
printStudent(&s);
cout<<s.name<<" " << s.age << endl;
system("pause");
return 0;
}