C++ struct的4种定义方式

结构体将不同的数据烈性整合在一起构成一个新的类型,相当于数据库中一条记录,比如学生结构体,整合了学号,姓名等信息。结构体的好处就是可以对这些信息进行整体管理操作,类似面向对象中类的属性,有了结构体,就可以更好抽象描述一个类别,个人感觉类就是由结构体发展而来的,在c/c++中,结构体声明的关键字为struct.

语法:

第一种语法表示

struct 结构体名称{
   数据类型 member1;
   数据类型 member2;
};

#include<iostream>
using namespace std;
struct Student{
    int sNo;
    char name[10];
};
int main(){
    struct Student stu;
	//stu.name="zhangsan";//这种赋值方式是不对的
	strcpy(stu.name, "zhangsan");
	stu.sNo=18;
	cout<<stu.name<<endl;
	cout<<stu.sNo<<endl;
}

第二种语法表示

typedef struct 结构体名称{
   数据类型 member1;
   数据类型 member2;
}结构体名称别名;
这种方式在声明结构体变量时有两种方式。

第一种:struct 结构体名称 构体变量名
第二种:结构体名称别名 结构体变量名

原因:这里使用了typedef关键字,此关键字的作用就是声明数据类型的别名,方便用户编程,所以这里用了之后,结构体名称别名就相当于struct 结构体名称。在声明结构体变量时,就无需写struct了。

#include<iostream>
using namespace std;
 typedef struct Student{
    int sNo;
    char name[10];
} stud;
int main(){
    struct Student stu;//方式一
	stud stu1;//方式二,以结构体别名声明一个结构变量stu1,此处可以省略关键字struct
	//stu.name="zhangsan";//这种赋值方式是不对的
	strcpy(stu.name, "zhangsan");
	stu.sNo=18;
	stu1.sNo=19;
	cout<<stu.name<<endl;
	cout<<stu.sNo<<endl;
	cout<<stu1.sNo<<endl;
}

第三种方式

struct 结构体名称{
   数据类型 member1;
   数据类型 member2;
}结构体变量;

#include<iostream>
using namespace std;
 struct Student{
    int sNo;
    char name[10];
} stu;//这里相当于直接声明并定义了一个结构体变量stu
int main(){
    //struct Student stu;//错误,这里就不可以再这样声明变量
	//stud stu1;///错误,
	//stu.name="zhangsan";//这种赋值方式是不对的
	strcpy(stu.name, "zhangsan");
	stu.sNo=18;	
	cout<<stu.name<<endl;
	cout<<stu.sNo<<endl;
	//cout<<stu1.sNo<<endl;
}

第四种方式

struct {
   数据类型 member1;
   数据类型 member2;
}结构体变量名;

此方式是匿名结构体,在定义时同时声明2个结构体变量,但不能在其它地方声明,因为我们无法得知该结构体的标识符,所以就无法通过标识符来声明变量。

 #include<iostream>
using namespace std;
 struct {
    int sNo;
    char name[10];
} stu1,stu2;//这里相当于直接声明并定义了2个结构体变量stu1,stu2
int main(){    
	strcpy(stu1.name, "zhangsan");
	stu1.sNo=18;
	stu2.sNo=8;
	cout<<stu1.name<<endl;
	cout<<stu1.sNo<<endl;
	cout<<stu2.sNo<<endl;
}
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Mr顺

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值