Class with no name

╄→гoц情女王★ 提交于 2019-12-04 17:43:52

The grammar goes

class-specifier:
    class-head { member-specification_opt }

class-head:
    class-key attribute-specifier-seq_opt class-head-name class-virt-specifier-seq_opt base-clause_opt
    class-key attribute-specifier-seq_opt base-clause_opt

class-key:
    class
    struct
    union

In your case, the second production of class-head is used -- no class-name is involved.

The identifier is omitted entirely, so the question of correct grammar for the identifier is moot. Nothing in the description says the identifier must be present. Anonymous classes are probably allowed for consistency with C struct rules, which allows constructs such as:

typedef struct { int i; } Foo;

struct { int x, y; } points[] = { {1, 2}, {3, 4} };

I don't think I've ever seen this done for a class.

class {public: int i;}

is quite useless, but you can specyfy a class without a name and then create instances of this class. Knowing that you can use the following:

class {public: int i;} a,b,c;
a.i = 5;
b.i = 4;
c.i = 3;
cout<<a.i<<" "<<b.i<<" "<<c.i;

You can use this inside a function too (as an anonimous class), so knowing that you can use something like this:

void x()
{
    class {public: int i;} a,b,c;
    a.i = 5;
    b.i = 4;
    c.i = 3;
    cout<<a.i<<" "<<b.i<<" "<<c.i;
}

int main() {
    x();
}

The code class { int i; }; is fully-standard conformant.You've quoted the irrelevant reference from the Standard which has nothing to do with anonymous class.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!