struct:
结构体 用户自己定义的数据类型
struct 数据类型名{参数列表 };
struct student {
string name;
int age;
int score;
};
使用方法:
定义的同时就可以给它赋值
#include"iostream"
using namespace std;
struct student {
string name;
int age;
int score;
};
int main() {
struct student s1 = { "小王",18,100 };
cout << s1.age <<" "<< s1.name <<" "<< s1.score << endl;
system("pause");
return 0;
}
数组结合:
#include"iostream"
using namespace std;
struct student {
string name;
int age;
int score;
};
int main() {
struct student arr[3] = { {"小王",18,100}, {"老王",50,60}, {"王阿姨",49,65}};
for (int i = 0; i < 3; i++)
cout << arr[i].name<<" "<<arr[i].age<<" "<<arr[i].score << endl;
system("pause");
return 0;
}
指针结合:
指针引用 “->”
#include"iostream"
using namespace std;
struct student {
string name;
int age;
int score;
};
int main() {
struct student s1 = { "小王",18,100 };
struct student* p;
p = &s1;
cout << p->name<<" "<<p->age<<" "<<p->score << endl;
system("pause");
return 0;
}
嵌套使用:
#include"iostream"
using namespace std;
#include<string>
struct student {
string name;
int age;
int score;
};
struct teacher {
string name;
int id;
int age;
student stu;
};
int main() {
struct teacher s2 = { "miss刘",1255,25,{"小王",18,100} };
cout << s2.stu.age << endl;
system("pause");
return 0;
}
值传递:
#include"iostream"
using namespace std;
struct student {
string name;
int age;
int score;
};
void printfstudent(struct student s1) {
cout << s1.name << " " << s1.age << " " << s1.score << endl;
}
int main() {
struct student s1={"小王",18,100};
printfstduent(s1);
system("pause");
return 0;
}
地址传递:
#include"iostream"
using namespace std;
struct student {
string name;
int age;
int score;
};
void printfstudent2(struct student* s1) {
cout << s1->name << " " << s1->age << " " << s1->score << endl;
}
int main() {
struct student s1={"小王",18,100};
printfstudent2(&s1);
system("pause");
return 0;
}