C++结构体

2020-05-08  本文已影响0人  JuliusL

概念

结构体属于用户自定义的数据类型,允许用户存储不同的数据类型

定义和使用

语法:struct 结构体名{ 结构体成员列表 };
通过结构体创建变量的方式有三种

创建结构体的时候struct可以省略。

struct Student{
  string name;
} s1; //可以在定义的时候顺便创建变量

int main(){
  struct Student s1; 
  s1.name = "Jam";
  return 0;
}

结构体数组

语法:struct 结构体名 数组名[元素个数]={ {},{},{}... };

struct Student{
  string name;
  int age;
}
int main(){
  Student arr[3] = {
    {"Jam",18},
    {"Lucy",18},
    {"Lily",18},
  };
  
  //给结构体中的数组赋值
  arr[0].name = "王五";
  arr[0].age = 20;
  return 0;
}

结构体指针

利用操作符->可以通过结构体指针访问结构体属性。

struct Student{
  string name;
  int age;
}
int main(){
  Student s = {"张三",19};
  //通过指针指向结构体变量
  Student * p = &s;
  //通过指针访问结构体变量中的数据
  cout <<  p->name << p->age << endl;

结构体做函数参数

1,结构体做函数参数时用值传递,不会改变实参的实际值。
2,结构体做函数参数用指针传递,会改变实参的实际值。

结构体中的const使用场景

将函数的形参改为指针,不会复制新的副本出来,可以减少内存空间。
可是这样做通常的业务是不能修改实际值的。
为了避免误操作,在形参之前加上const关键字可以避免。

void printStudent(const Student *s){
  //在这里如果修改了s->age会报错!
  s->age = 18;
}
上一篇 下一篇

猜你喜欢

热点阅读