/*C/C++ 数组允许定义可存储相同类型数据项的变量,但是结构是 C++ 中另一种用户自定义的可用的数据类型,它允许您存储不同类型的数据项。*/
#include <iostream>
#include <string>
using namespace std;
//1.定义结构体
struct Food { string name; int price; };
struct Member { string name; int age; int score; struct Food f1; };
void Printstruct(Member m) { cout <<"函数中"<< m.name <<endl; };
int main() {
//2.结构体创建,通过(.)赋值与访问。
//2.1
struct Member m1;
m1.name = "Jack";
m1.age = 20;
m1.score = 100;
//2.2
struct Member m2 = { "mick",19,60 };
cout << m1.name << endl;
cout << m2.name << endl;
cout << endl;
/*3.结构体数组*/
struct Member arr[3] = {
{"Ruby",20,33},
{"Python",22,22},
{"Java",55,55}
};
for (int i = 0; i < 3; i++)
{
cout << arr[i].name;
cout << arr[i].age;
cout << arr[i].score;
cout << endl;
}
/*4.嵌套结构体*/
struct Member m3 = { "C++",66,77, {"Apple",2000} };
cout << "嵌套结构体" << endl;
cout << m3.age << m3.score << m3.f1.name << m3.f1.price << endl;
/*5.结构体当函数参数*/
Printstruct(m3);
return 0;
}
/*C/C++ 数组允许定义可存储相同类型数据项的变量,但是结构是 C++ 中另一种用户自定义的可用的数据类型,它允许您存储不同类型的数据项。*/
#include <iostream>
#include <string>
using namespace std;
//1.定义结构体
struct Food { string name; int price; };
struct Member { string name; int age; int score; struct Food f1; };
void Printstruct(Member m) { cout <<"函数中"<< m.name <<endl; };
int main() {
//2.结构体创建,通过(.)赋值与访问。
//2.1
struct Member m1;
m1.name = "Jack";
m1.age = 20;
m1.score = 100;
//2.2
struct Member m2 = { "mick",19,60 };
cout << m1.name << endl;
cout << m2.name << endl;
cout << endl;
/*3.结构体数组*/
struct Member arr[3] = {
{"Ruby",20,33},
{"Python",22,22},
{"Java",55,55}
};
for (int i = 0; i < 3; i++)
{
cout << arr[i].name;
cout << arr[i].age;
cout << arr[i].score;
cout << endl;
}
/*4.嵌套结构体*/
struct Member m3 = { "C++",66,77, {"Apple",2000} };
cout << "嵌套结构体" << endl;
cout << m3.age << m3.score << m3.f1.name << m3.f1.price << endl;
/*5.结构体当函数参数*/
Printstruct(m3);
return 0;
}