What does the name after the closing class bracket means?

后端 未结 4 1648
庸人自扰
庸人自扰 2021-02-08 14:45

I\'ve encountered this code example and I remembered I\'ve seen it before and I didn\'t know what it is for and what it does? I\'ve searched on the internet but without luck.

相关标签:
4条回答
  • 2021-02-08 15:37
    } g_c;
    

    Here g_c is declared to be an object of the class type C.

    Such construct enables you to create object(s) of unnamed type as:

    class  //Nameless class!
    {
       //data members
    
    }obj1, obj2;
    

    In this example, obj1 and obj2 are declared to be objects of a class type which has not been given any name — the class is nameless! In such situation, you cannot declare objects in a conventional sense (i.e Type obj1, obj2; sense). So this construct helps you do that.

    You can even derive from other named classes while being nameless (and declaring the objects of the nameless class):

    class : public A, public B //Nameless class is deriving from A and B
    {
       //data members
    
    }obj1, obj2;
    

    In short, this construct ensures that the user wouldn't be able to create more objects than intended, unless some evil programmer uses/misuses/abuses C++11 (or template) as:

    decltype(obj1) obj3; //hehe!
    

    Hope that helps!

    0 讨论(0)
  • 2021-02-08 15:39

    You declare variables using the format type variable_name;. For example:

    A x;
    

    Where A may be the name of a class.

    But instead of using a pre-existing class type, you can also define the class at the same time as you declare a variable of the new class's type:

    class { ... } x;
    

    or define the class and give it a name:

    class A { ... } x;
    

    In C++ it is common to just define the class and give it a name, but leave off the variable:

    class A { ... };
    

    but you don't have to leave off the variable.

    0 讨论(0)
  • 2021-02-08 15:44

    It's shorthand for:

    class C
    {
        ....
    };
    
    C g_c;
    
    0 讨论(0)
  • 2021-02-08 15:49

    That's just a way of creating objects of that type of Class. Structs mostly use them to initialize new variables.

    0 讨论(0)
提交回复
热议问题