C++三种形式引用结构体成员变量

    技术2025-12-28  10

    三种形式分别为:

    结构体变量名.成员名

    指针变量名->成员名

    (*指针变量名).成员名(注意:*不能省略因.的结合性大于*)

     

    #include <iostream> using namespace std; struct student1 { int Code; char Name[20]; char Sex; int Age; }; //只定义了其的名字但未对其进行初始化 struct student1 Stu[2]={{1,"zhangsan",'M',21},{2,"lisi",'M',22}}; int main() { struct student1 *pstu; cout<<"The Second Form Refer To Structure Variables: "<<endl; for(pstu=Stu;pstu<Stu+2;pstu++) cout<<pstu->Code<<"\t"<<pstu->Name<<"\t"<<pstu->Sex<<"\t"<<pstu->Age<<endl; cout<<"The First Form Refer To Structure Variables:"<<endl; for(int i=0;i<2;i++) cout<<Stu[i].Code<<"\t"<<Stu[i].Name<<'\t'<<Stu[i].Sex<<'\t'<<Stu[i].Age<<endl; cout<<"The Third Form Refer To Sturucture Variables:"<<endl; for(pstu=Stu;pstu<Stu+2;pstu++) cout<<(*pstu).Code<<"\t"<<(*pstu).Name<<"\t"<<(*pstu).Sex<<"\t"<<(*pstu).Age<<endl; return 0; }

     

    Processed: 0.013, SQL: 9