數據封裝---結構體

定義:

struct  結構體類型名

{

字段聲明;

};

在定義結構體類型時,字段名可與程序中的變量名相同,在不同的結構體中也可以有相同的字段名,而不會發生混淆

結構體的成員的類型可以是任意類型,可以是整型,可以是整型、實型、也可以是數組,當然也可以是其他結構體類型。

事實上,一旦定義了一個結構體類型的變量,系統在分配內存時就會分配一塊連續的空間,一次存放它的每一個分量,這塊空間總的名字就是該變量的名字,每一小塊還有自己的名字,即字段名;

定義結構體:

Student stu1;       //Student是結構體類型名

stu1.chinese;      //訪問stu1中的chinese的字段

與普通變量一樣,結構體除了可以通過變量名直接訪問外也可以通過指針間接訪問,指針結構體的指針定義與普通指針定義一樣:

結構體類型名  *指針變量名;

也可以在定義結構體類型時直接定義指針變量:

struct  結構體類型嗎

{

字段聲明;

}  *結構體指針;


Student   stu1,*sp=&stu1;

sp=new Student;

訪問字段名方法(2種):

(*sp).name;

sp->name;


結構體數組:

Student   stuArray[10];

stuArray[1].name;

實例:

#include<iostream>
#include<cmath>
using namespace std;
struct pointT
{
double x,y;
};
pointT setPoint(double x,double y)
{
pointT p;
p.x=x;
p.y=y;
return p;
}
double getX(pointT &p)
{
return p.x;
}
double getY(pointT &p)
{
return p.y;
}
void showPoint(const pointT &p)
{
cout<<"("<<p.x<<","<<p.y<<")";
}
double distancePoint(const pointT &p1,const pointT &p2)
{
return sqrt((p1.x-p2.x)*(p1.x-p2.x)+(p1.y-p2.y)*(p1.y-p2.y));
}
int main(void)
{
pointT p1,p2;
p1=setPoint(1,1);
p2=setPoint(2,2);
cout<<getX(p1)<<"  "<<getY(p2)<<endl;
showPoint(p1);
cout<<" - >";
showPoint(p2);
cout<<" = "<<distancePoint(p1,p2)<<endl;
return 0;
}

結果:

1  2
(1,1) - >(2,2) = 1.41421
請按任意鍵繼續. . .


簡單鏈表實例:

#include<iostream>
#include<cmath>
using namespace std;
struct linkRec
{
int data;
linkRec *next;
};


int main(void)
{
int x;
linkRec *head,*p,*rear;
head=rear=new linkRec;
while(true)
{
cin>>x;
if(x==0)
break;
p=new linkRec;
p->data=x;
rear->next=p;
rear=p;
}
rear->next=NULL;
cout<<"鏈表的內容爲:"<<endl;
p=head->next;
while(p!=NULL)
{
cout<<p->data<<'\t';
p=p->next;
}
cout<<endl;
return 0;
}

結果:

1
2
3
4
0
鏈表的內容爲:
1       2       3       4
請按任意鍵繼續. . .

發佈了23 篇原創文章 · 獲贊 11 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章