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

2019-03-22 22:25发布

问题:

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

Code here:

#include <iostream>

auto func()
{
    class // no name
    {
      public:
             int val;
    } a;

    a.val = 5;

    return a;
}

int main()
{
    std::cout << func().val << std::endl;
    return 0;
}

So, Is it valid in C++?

Also, I am curious to know, Is it possible to use anonymous classes in C++?

回答1:

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 <object>. 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.



回答2:

Not only that, you can create more instances of the class by using decltype.

#include <iostream>

class 
{
   public:
      int val;
} a;


int main()
{
   decltype(a) b;
   a.val = 10;
   b.val = 20;

   std::cout << a.val << std::endl;
   std::cout << b.val << std::endl;
   return 0;
}

Output:

10
20


回答3:

It was always possible to write something like this:

typedef struct { int a; } type;

Now, if you look at struct { int a } part, this is an anonymous struct. In C++, there's basically no difference between structs and classes (Except the default access modifiers). So, it's possible to have anonymous structs/classes.