typedef修饰struct用法详解

typedef 修饰 struct ,因为在C和C++中struct中意义不完全一样,所以我们分两块姜,在C中typedef修饰struct和C++中typedef修饰struct。

一:C中typedef修饰struct
在C中定义一个结构体类型要用typedef:
    typedef struct Student
    {
    int a;
    }Stu;
于是在声明变量的时候就可:Stu stu1;(如果没有typedef就必须用struct Student stu1;来声明)这里的Stu实际上就是struct Student的别名。Stu==struct Student。另外这里也可以不写Student(于是也不能struct Student stu1;了,必须是Stu stu1;)
    typedef struct
    {
    int a;
    }Stu;
应用实例代码:

#include <stdio.h>

struct Student
{
        int id;
};

typedef struct Teacher
{
        char *subject;
}T;
int main()
{
        struct Student stu1;
        stu1.id = 1;
        printf("%d\n",stu1.id);

        T t1;
        t1.subject = "math";
        printf("%s\n",t1.subject);
        return 0;
}

二:C++中typedef修饰struct
因为在C++是面向对象的语言,所以C++中有类的概念,而struct在默认情况下就约等于class了。只是有一些小小的区别,就是成员默认的访问级别是公有的,而class默认私有的。
回归正题。C++中typedef修饰struct的时候会出现如下情况。
    struct Student
    {
    int a;
    }stu1;//stu1是一个变量

typedef struct Student2
    {
    int a;
    }stu2;//stu2是一个结构体类型=struct Student

使用时可以直接访问stu1.a
但是stu2则必须先 stu2 s2;
然后 s2.a=10;

  • 5
    点赞
  • 37
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值