C/C++ 结构体Struct区别
struct关键字是一种程序定义的数据类型,用户可以自定义其中的数据项
C语言的Struct
C中的struct用来存放一组不同的数据,其中的数据项只能为变量,而不能为函数
定义格式
struct type_name {
member_type1 member_name1;
member_type2 member_name2;
member_type3 member_name3;
...
}
定义变量
C语言中初始化结构体变量有4种方式,例如定义一个结构体Employee
struct Employee
{
int id {};
int age {};
double wage {};
};
并对其进行初始化
// 1
struct Employee joe, mary; //定义两个变量
joe.id = 123;
joe.age = 32
joe.wage = 20000;
//2
struct Employee joe(123, 32, 20000), mary(234, 29, 8000); //定义变量并初始化
//3
struct Employee
{
int id {};
int age {};
double wage {};
}mary, joe = {123, 32, 20000} //将变量放在结构体定义最后,大括号后分号前
//4
struct {
int id {};
int age {};
double wage {};
}joe = {123, 32, 20000} // 若后续不再定义此结构体变量,可忽略结构提名称(Employee)
C++中的struct
C++中的struct继承至c中的struct,因此有相似也有不同
由于C++既可以面向过程也可以面向对象编程,因此c++中的struct与class类似,可以包含成员变量,也可以包含成员函数
定义结构体
struct Employee
{
int id {};
int age {};
double wage {};
Employee(){ //构造函数, 名称必须与结构体相同
id = 123
age = 32;
wage = 20000;
};
};
定义变量
//C++ 变量初始化可以省略`struct`关键字
struct Employee joe;
Employee joe;
c++中的struct与class基本通用,但又有不同
class默认成员为private属性,而struct默认成员为public属性class继承默认为private继承, 而struct继承默认为public继承class可以使用模板,而struct不能

浙公网安备 33010602011771号