C/C++ 中定义结构体的几种方法、初始化 以及别名的定义

定义结构体

定义结构体 Student 并调用里面的变量age

C版本:

  • 方法1. 定义结构体

struct Student{
int id;
int age;
};
调用:
struct Student stu;
int b = stu.age;

  • 方法2.定义结构体

typedef struct Student {
int id;
int age;
}Stud;
调用
Stud stu;
stu.age = 10;
int b = stu.age;
如果没有typedef ,则C语言中需要用struct Student stu来定义对象。

Stud 相当于是struct Student的别称

  • 方法3.省略Student

typedef struct {
int id;
int age;
}Stud;
调用
Stud stu;
stu.age = 10;
int b = stu.age;

C++版本

直接定义

  • 方法1. 有初始化
    struct Stud {

int id;
int age;
{
id = 1;
age = 10;
};
调用
Stud stu;
stu.age = 10;
int b = stu.age;

  • 方法2.使用typedef进行时,有别名,需要定义对象。

typedef struct Student {
int id;
int age;
Student ()
{
id = 1;
age = 10;
}
}Stud;
调用时
Stud stu;
stu.age = 10;
int b = stu.age;

  • 3.使用using 并初始化

using Student = struct {
int id = 1;
int age = 10;
};
调用
Student stu;
stu.age = 10;
int b = stu.age;

【定义别名】

typedef 旧的 新的
注意使用typedef

方法1. typedef std::vector name_list;

方法2.using name_list = std::vector;

方法3. define pii (3.333333)
添加链接描述
添加链接描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值