什么结构体
用户可以自定义的数据类型,允许用户存储不同数据类型
怎么用?
// myCppPro.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include<iostream>
#include <string>
using namespace std;
struct Student
{
string name;
int age;
int score;
};
int main(int argc, _TCHAR* argv[])
{
Student student;
//第一种赋值方式
student.name="张三";
student.age=18;
student.score=100;
//第二种赋值方式
Student student2={"李四",19,200};
cout <<"姓名:"<<student2.name<<endl;
//访问
system("pause");
return 0;
}
结构体数组
// myCppPro.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include<iostream>
#include <string>
using namespace std;
struct Student
{
string name;
int age;
int score;
};
int main(int argc, _TCHAR* argv[])
{
Student studentArry[2]=
{
{"张三",18,20},
{"张一",18,20}
};
for (int i=0;i<sizeof(studentArry)/sizeof(studentArry[0]);i++)
{
cout<<studentArry[i].name<<endl;
}
//访问
system("pause");
return 0;
}
结构体指针
通过->
来访问结构体
// myCppPro.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include<iostream>
#include <string>
using namespace std;
struct Student
{
string name;
int age;
int score;
};
int main(int argc, _TCHAR* argv[])
{
Student student={"张三",18,20};
Student*p=&student;
cout<<"姓名:"<<p->name<<endl;
//访问
system("pause");
return 0;
}
输出: