c++構造体

8162 ワード

struct Student               //         Student

{ int num;                 //        num

  char name[20];           //        name,    20   

  char sex;                //        sex

  int age;                 //        age 

  float score;             //          

  char addr[30];           //        addr,    30   

};                        //       

1、上记の1つの构造体を宣言します:メモリの中でそれぞれ63バイト(4+20+1+4+4+30=63)を占めます
2、構造体配列:
struct Student                  

{ int num;

  char name[20];

  char sex;

  int age;

  float score;

  char addr[30];

}sty[3]={{10101,″Li Lin″,′M′,18,87.5,″103 Beijing Road″},

{10102,″Zhang Fun″,′M′,19,99,″130 Shanghai Road″},

{10104,″Wang Min″,′F′,20,78.5,″1010,Zhongshan Road″}};

3.構造体変数へのポインタ:
使いやすく直感的に使用するために、C++は、ポインタpが現在指している構造体変数のメンバーnumを表すp->numのような構造体変数を指す演算子->を提供します.p->numと(*p).num等価.同様に、p->nameは(*p)に等価である.name.
すなわち、以下の3つの形式は等価である:1構造体変数.メンバー名.例えばstu.num.    ② (*p).メンバー名.如(*p).num.③p->メンバー名.p->numのようです.「->」は指向演算子と呼ばれます.p->nはpが指す構造体変数のメンバーnの値を得るいくつかの演算を解析してください.p->n++は、pが指す構造体変数のメンバーnの値を得、この値が切れたら1を加算する.++p->nは、pが指す構造体変数のメンバーnの値を得、1を加えて使用する.
#include <iostream>

#include <string>

using namespace std;

int main( )

{  
  struct Student // student     {  int num;        string name;        char sex;        float score; };   Student stu; // Student stu   Student *p=&stu; // p Student stu   stu.num=10301; // stu   stu.name=″Wang Fun″; // string   stu.sex=′f′;   stu.score=89.5;   cot<<stu. num<<″ ″<<stu.name<<″ ″<<stu.sex<<″ ″<<stu.score<<endl;   cout<<(*p)>num<<″ ″<<(*p).name<<″ ″<<(*p).sex<<″ ″<<(*p).score<<endl;   return 0; }

4、構造体生成チェーンテーブル:
  
#define NULL 0   

#include <iostream> 

struct Student

{ long num;

  float score;

  struct Student *next;

};

int main( )

{  Student a,b,c,*head,*p;

  a. num=31001; a.score=89.5;             //   a num score    

  b. num=31003; b.score=90;               //   b num score    

  c. num=31007; c.score=85;               //   c num score    

  head=&a;                                //   a          head

  a.next=&b;                              // a.next=&b;                              //   b       a   next  

  b.next=&c;                              //   c       b   next  

  c.next=NULL;                            //   next           

  p=head;                                 // p    a  

  do        

  {  cout<<p->num<<″  ″<<p->score<<endl;     //  p        

     p=p->next;                              // p        

  } while(p!=NULL);                         //   c   p   NULL 

  return 0;

}