结构体
struct student { string name; int age; int score; };
创建结构体变量
1.
struct student a; a.name = "张三"; a.age = 18; a.score = 100; cout << a.name << " " << a.age << " " << a.score << " " << endl;
2.
struct student a = { "张三",18,100 }; cout << a.name << " " << a.age << " " << a.score << " " << endl;
3.
struct student { string name; int age; int score; }a; int main() { a.name = "张三"; a.age = 18; a.score = 100; cout << a.name << " " << a.age << " " << a.score << " " << endl; return 0; }
创建结构体数组顺便给结构体数组中的元素赋值
#include<iostream> #include<string> using namespace std; struct student { string name; int age; int score; }; int main() { struct student a[3] = { {"张三",18,100}, {"李四",19,99}, {"王五",20,98} }; a[0].name = "老六"; a[1].name = "头七"; a[2].name = "王八"; for(int i = 0; i < 3; i++) { cout << " " << a[i].name << " " << a[i].age << " " << a[i].score << endl; } return 0; }
结构体指针
struct student a = { "张三",18,100 }; student* p = &a; cout << " " << p->name;
结构体做函数参数
1.值传递
void printstudent(struct student a) { cout << a.name << " " << a.age << " " << a.score << " " << endl; } int main() { struct student a = { "张三",18,100 }; printstudent(a); return 0; }
2.地址传递
#include<iostream> #include<string> using namespace std; struct student { string name; int age; int score; }; void printstudent(struct student *p) { cout << p->name << " " << p->age << " " << p->score << " " << endl; } int main() { struct student a; a.name = "张三"; a.age = 18; a.score = 100; struct student* p = &a; printstudent(&a); return 0; }