Is it possible to use anonymous classes in C++?

前端 未结 2 939
抹茶落季
抹茶落季 2021-02-12 06:29

I have seen anonymous classes in C++ code on Quora. It\'s successfully compiled and run.

Code here:

#inclu         


        
2条回答
  •  旧时难觅i
    2021-02-12 07:07

    In C++, an anonymous union is a union of this form:

     union { ... } ;
    

    It defines an unnamed object of an unnamed type. Its members are injected in the surrounding scope, so one can refer to them without using an . prefix that otherwise would be necessary.

    In this sense, no anonymous classes (that are not unions --- in C++ unions are classes) exist.

    On the other hand, unnamed classes (including structs and unions) are nothing unusual.

    union { ... } x;
    class { ... } y;
    typedef struct { ... } z;
    

    x and y are named object of unnamed types. z is a typedef-name that is an alias for an unnamed struct. They are not called anonymous because this term is reserved for the above form of a union.

    [](){}
    

    Lambdas are unnamed objects of unnamed class types, but they are not called anonymous either.

    提交回复
    热议问题