创建结构体
#include<iostream>
using namespace std;
#include<string>
struct Godv
{
string name;
int age;
}gg3;//第三种创建方式
int main()
{
//第一种创建方式
Godv gg1;
gg1.age = 18;
gg1.name = "godv";
cout << "gg1 :" << gg1.age << gg1.name << endl;
//第二种创建方式
Godv gg2 = { "goda",19 };
cout << "gg2 :" << gg2.age << gg2.name << endl;
gg3.name = "godb";
gg3.age = 20;
cout << "gg3 :" << gg3.age << gg3.name << endl;
return 0;
}
结构体数组
跟一半数组的使用一样 这里仅规范一下编写风格
Godv ggArr[3] =
{
{"godv",18},
{"goda",19},
{"godb",20}
};
结构体指针 ->
Godv gg4 = { "godc",21 };
Godv* p = &gg4;
cout << "gg4 :" << p->age << p->name << endl;
利用const关键字防止误操作
void readGodv(const Godv * p)
{
cout << "Godv :" << p->age << p->name << endl;
}
最后附赠一个结构体的小demo
#include <iostream>
#include <string>
#include <ctime>
using namespace std;
struct Student
{
string name;
int score;
};
struct Teacher
{
int id;
string name;
Student stus[4];
};
void writeData(Teacher *p,int len)
{
//赋值
string nameSpace = "ABCD";
for (int i = 0; i < len; i++)
{
p->id = i;
p->name = "Tea_";
p->name += nameSpace[i];
Student* s = p->stus;
for (int j = 0; j < 4; j++)
{
s->name = "Stu_";
s->name += nameSpace[j];
// int random = rand() % 60; 0~59
int random = rand() % 61 + 40; //40~100
s->score = random;
s++;
}
p++;
}
}
void showData(Teacher* p, int len)
{
for (int i = 0; i < len; i++)
{
Student* s = p->stus;
cout << "老师:" << p->id << p->name << endl;
for (int j = 0; j < 4; j++)
{
cout << "\t学生:" << s->name << s->score << endl;
s++;
}
p++;
}
}
int main()
{
//随机数种子
srand((unsigned int)time(NULL));
Teacher tea[3];
int len = sizeof(tea) / sizeof(tea[0]);
writeData(tea, len);
showData(tea,len);
return 0;
}