zoukankan      html  css  js  c++  java
  • struct和typedef struct在c++中的用法

    #include<iostream>
    using namespace std;
    struct test{
    int a;
    
    }test;
    //定义了结构体类型test,声明变量时候直接test d;
    
    //如果用typedef的话,就会有区别
    
    struct test1{
    int a;
    }test11;    //test11是一个变量
    
    typedef struct test2{
    int a;
    }test22;    //test22 是一个结构体类型。==struct test2
    
    //使用的时候,可以直接访问test11.a;
    //test22必须先声明一个变量。test22  s22; 然后s22.a=1;这样来访问
    
    int  main(){
    //test q;  //会报错error: must use 'struct' tag to refer to type 'test' in this scope
    struct test q;
    q.a=10;
    
    cout<<"q:"<<q.a<<endl;
    
    test1 d;
    d.a=11;
    
    cout<<"d:"<<d.a<<endl;
    
    //test11 f;   会报错error: use of undeclared identifier 'f' test11 f;
    
    //f.a=14;
    //cout<<"f:"<<f.a<<endl;
    
    test11.a=11111;   //test11是变量,可以直接赋值
    cout<<"test11.a"<<test11.a<<endl;
    
    test2 w;
    w.a=12;
    
    cout<<"w:"<<w.a<<endl;
    
    test22 r;
    r.a=13;
    
    cout<<"r:"<<r.a<<endl;
    //可以用test2 w声明变量,也可以 test22 r;声明变量。和c语言中不同。c语言中test2 w 声明会把错的
    
    return 0;
    }

    来自网络的一个解释参考:

     typedef struct tagMyStruct
        { 
         int iNum;
         long lLength;
        } MyStruct;

        上面的tagMyStruct是标识符,MyStruct是变量类型(相当于(int,char等))。

        这语句实际上完成两个操作:

          1) 定义一个新的结构类型

        struct tagMyStruct
        {   
         int iNum; 
         long lLength; 
        };

      分析:tagMyStruct称为“tag”,即“标签”,实际上是一个临时名字,不论是否有typedef ,struct 关键字和tagMyStruct一起,构成了这个结构类型,这个结构都存在。

      我们可以用struct tagMyStruct varName来定义变量,但要注意,使用tagMyStruct varName来定义变量是不对的,因为struct 和tagMyStruct合在一起才能表示一个结构类型。

      2) typedef为这个新的结构起了一个名字,叫MyStruct。

        typedef struct tagMyStruct MyStruct;

      因此,MyStruct实际上相当于struct tagMyStruct,我们可以使用MyStruct varName来定义变量。

      2.

        typedef struct tagMyStruct
        { 
         int iNum;
         long lLength;
        } MyStruct;

        在C中,这个申明后申请结构变量的方法有两种:

        (1)struct tagMyStruct 变量名

        (2)MyStruct 变量名

        在c++中可以有

        (1)struct tagMyStruct 变量名

        (2)MyStruct 变量名

        (3)tagMyStruct 变量名

  • 相关阅读:
    POJ 基本算法(3)
    给定范围的素数筛选(POJ 2689)
    无向图、有向图的最小环
    第k短路和A*
    HDU 4302 Holedox Eating (set + iterator)
    笛卡尔树
    HDU 多校联合第一场
    HDU 多校联合第二场
    POJ 图算法(3)
    POJ 1038 Bugs Integrated, Inc. (状态dp)
  • 原文地址:https://www.cnblogs.com/vincentqliu/p/typedef_struct_cplus.html
Copyright © 2011-2022 走看看