C++结构体定义 & 创建 & 赋值 & 结构体数组 & 结构体指针 & 结构体嵌套结构体 & 结构体做函数参数 & 结构体中的const使用场景 |
您所在的位置:网站首页 › 结构体数组里的数组怎么输 › C++结构体定义 & 创建 & 赋值 & 结构体数组 & 结构体指针 & 结构体嵌套结构体 & 结构体做函数参数 & 结构体中的const使用场景 |
一.结构体是什么?
struct是自定义数据类型,是一些类型集合组成的一个类型。
二.结构体的定义方式
#include
using namespace std;
struct Student
{
string name;
int age;
int score;
};
三.创建结构体变量并赋值
方式一,先创建结构体变量,再赋值
// 创建结构体变量 , 此时可以省略struce关键字
struct Student s1;
// 给结构体变量赋值
s1.name = "zhangsan";
s1.age = 26;
s1.score = 100;
方式二,创建结构体变量的同时赋值
struct Student s2={"zhangsan",26,100};
方式三,创建结构体的时候顺便创建结构体变量
struct Student
{
string name;
int age;
int score;
}s3;
s3.name = "zhangsan";
s3.age = 26;
s3.score = 80;
四.结构体数组的定义和访问
#include
#include
using namespace std;
struct Student
{
string name;
int age;
int score;
};
int main()
{
struct Student stu_arr[3] =
{
{"张三",18,80},
{"李四",19,60},
{"王五",38,66}
};
// 给结构体的元素赋值
stu_arr[2].name = "赵六";
stu_arr[2].age = 20;
stu_arr[2].score = 98;
// 遍历结构体数组
for(int i=0;i
string name;
int age;
int score;
};
int main()
{
struct Student s = {"张三",18,100};
// 创建Student类型的指针
Student* p = &s;
// 用结构体类型的指针访问结构体的变量
cout
int id;
string name;
int age;
struct Student stu; // 要辅导的学生
};
int main()
{
Teacher t;
t.id = 1000;
t.name = "老王";
t.age = 50;
// 把学生的值也设置一下
t.stu.name = "小王";
t.stu.age = 26;
t.stu.score = 60;
cout
cout
struct Student s = {"张三",18,100};
// 创建Student类型的指针
Student* p = &s;
printStudent1(s);
printStudent2(p);
return 0;
}
当函数中有结构体形参时: 会把主函数的student赋值到下面函数的形参, 如果主函数中的student是个数组,那么也会将数组完全的复制一份给形参。 在函数中修改形参的值,不会影响主函数中该变量的值。如果用指针传参: 优点:用指针传参,一个指针只占四个字节,可以减少内存空间。不会复制新的副本出来。 缺点:在函数中修改结构体指针,会改变原来的值。为了防止在函数中误操作而修改结构体变量的值,传参的时候结构体遍历加 const即可。 例子: #include #include using namespace std; struct Student { string name; int age; int score; }; // 会把主函数的student赋值到下面函数的形参,如果主函数中的student是个数组,那么也会将数组完全的复制一份给形参。 void printStudent1(struct Student s) { s.age = 150; cout struct Student s = {"张三",18,100}; // 创建Student类型的指针 Student* p = &s; printStudent2(p); cout |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |