是否有可能在C ++中使用匿名类? [英] Is it possible to use anonymous classes in C++?

查看:140
本文介绍了是否有可能在C ++中使用匿名类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Quora的 C ++ 代码中见过匿名类。它已成功编译并运行。



代码位于

  #include< iostream> 

$ auto




$ public
int val;
} a;

a.val = 5;

返回a;
}

int main()
{
std :: cout<< func()。val<<的std :: ENDL;
返回0;

所以,它在C ++中有效吗?



另外,我很想知道,是否可以在C ++中使用匿名类?

是这种形式的联合:

<$ p $

p> union {...};

它定义了一个未命名类型的未命名对象。它的成员被注入到周围的范围中,所以可以在不使用< object>。前缀的情况下引用它们,否则将是必要的。



从这个意义上说,不存在匿名类(不是C ++联合中的联合是类)。

另一方面,

,无名类(包括结构和联合)没有什么特别的。

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

x y 是未命名类型的命名对象。 z 是一个typedef名称,它是未命名结构的别名。他们不被称为匿名,因为这个词是保留给上述联合的形式。

  [](){} 

Lambdas是未命名类类型的未命名对象,但它们也不被称为匿名对象。


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++?

解决方案

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.

这篇关于是否有可能在C ++中使用匿名类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆