1、結構體定義
首先定義一個學生結構體,如下所示:
struct Student
{int num;char name[32];char sex;int age;
};
接著在主函數中對學生進行聲明,如下所示:
#include<iostream>
using namespace std;struct Student
{int num;char name[32];};
int main()
{struct Student stu1;struct Student stu2;system("pause");return 0;
}
此時,stu1、stu2就具備結構體中變量的特性。
2、結構體初始化
結構體定義好后,進行結構體初始化,對變量進行賦值,如下所示:
int main()
{struct Student stu1;//結構體變量復制方式1stu1.num = 1;strcpy(stu1.name, "小明");cout<<"學號:"<<stu1.num<<"\n"<< "姓名:" << stu1.name << endl;//結構體變量復制方式2struct Student stu2 = {2,"小紅"};cout << "學號:" << stu2.num << "\n" << "姓名:" << stu2.name << endl;system("pause"); return 0;
}
運行結果如下:
?
上文如有錯誤,懇請各位大佬指正。