C++ typedef class use

后端 未结 2 947
余生分开走
余生分开走 2021-02-04 06:56

Why use a typedef class {} Name ?

I learnt this in IBM C++ doc, no hint to use here.

2条回答
  •  闹比i
    闹比i (楼主)
    2021-02-04 07:34

    This is a hangover from the 'C' language.

    In C, if you have

    struct Pt { int x; int y; };
    

    then to declare a variable of this struct, you need to do

    struct Pt p;
    

    The typedef helped you avoid this in C

    typedef struct { int x; int y; } Pt;
    

    Now you can do

    Pt p;
    

    in C.

    In C++, this was never necessary because

    class Pt { int x; int y; };
    

    allowed you to do

    Pt p;
    

    It provides no notational benefits in C++ as it does in C. OTOH, it leads to restrictions because this syntax does not provide any mechanism for construction, or destruction.

    i.e. you cannot use the name typedef name in the constructor or destructor.

    typedef class { int x; int y; } Pt;
    

    You cannot have a constructor called Pt, nor a destructor. So in essence, most of the time, you shouldn't do this in C++.

提交回复
热议问题