结构

定义结构

结构定义形式为: 例:
struct 标识符 struct employee
{ 类型 成员1; { char name[10];
类型 成员2; long code;
… double salary;
类型 成员n; char address[50];
}; char phone [10];
};
定义结构变量有三种方法:
1 声明类型之后声明变量。
struct employee
{ char name [ 10 ] ;
long code ;
double salary ;
char address [ 50 ] ;
char phone [ 20 ] ;
} ;employee worker1,worker2,*emp;
2 声明类型的同时声明变量。
struct employee
{ char name [ 10 ] ;
long code ;
double salary ;
char address [ 50 ] ;
char phone [ 20 ] ;
} worker1,worker2,*emp;
3 直接声明结构类型变量(无结构类型标识符)。
struct
{ char name [ 10 ] ;
long code ;
double salary ;
char address [ 50 ] ;
char phone [ 20 ] ;
} worker1,worker2,*emp;

访问结构

方式:1 结构变量.成员
2 指针访问 (1(*结构指针).成员 2结构指针->成员)
struct person
{
char name[20] ; unsigned long id; double salary;
} ;
int main ( )
{
person pr1 ;
person * pp ; // 定义结构指针
pp = & pr1 ; // 取结构变量地址
strcpy ( pp -> name , “David Marat” ) ; // 对结构成员赋值
pp -> id = 987654321 ;
pp -> salary = 335.0 ;
cout << pp -> name << ‘\t’ << pp -> id << ‘\t’ << pp -> salary << endl ;
}
3 类型相同的结构变量可以整体赋值
struct weather
{ double temp; double wind; } yesterday ;
int main ( )
{ weather today ;
yesterday . temp = 10.5 ;
yesterday . wind = 3.1 ;
today = yesterday ; // 结构变量整体赋值
cout << “Temp = ” << today . temp << endl ;
cout << “Wind = ” << today . wind << endl ;
}

结构数组

数组的元素类型为结构类型时,称为结构数组。
struct S_type
{ int a; double x; };
S_type S_ary[10];
S_ary是一个有10个元素的数组,元素类型是S_type。
数组的每一个元素包含两个数据成员。
S_ary[0].a S_ary[0].x
S_ary[1].a S_ary[1].x
……
S_ary[9].a S_ary[9].x

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值