天天看点

C++结构体与指针

结构体指针

作用:通过指针访问结构体中的成员

#include <iostream>

#include <string>

using namespace std;

//结构体指针

//定义学生的结构体

struct student

{

       string name;//姓名

       int age;//年龄

       int score;//分数

};

int main()

{

       //创建学生结构体变量

       struct student s={ "张三",18,100 };

       //通过指针指向结构体变量

       struct student *p = &s;

       //通过指针访问结构体变量指哪个的数据

       //通过结构体指针访问属性需要利用->

       cout << " 姓名:" << p->name

              << " 年龄:" << p->age

              << " 分数:" << p->score << endl;

       return 0;

}