通过指针访问结构体中的成员,利用符号 -> 可以通过结构体指针访问结构体属性。
#include<iostream>
using namespace std;
#include<string>
/*1.结构体指针*/
struct MyStruct
{
string name;
int age;
int score;
};
int main()
{
/*创建学生结构体变量*/
struct MyStruct s1 = { "小叶 ",18,200 };
/*通过指针指向结构体变量*/
// struct MyStruct int * p = &s; //错误
struct MyStruct * p = &s1;
/*通过指针访问结构体变量中的数据*/
cout << "姓名: " << p->name << " 年龄: " << p->age << " 分数: " << p->score << endl;
return 0;
}