What's actually going on in this AnonymousClass(variable) declaration?

后端 未结 3 925
死守一世寂寞
死守一世寂寞 2020-12-19 07:35

Trying to compile:

class AnonymousClass
{
public:
    AnonymousClass(int x)
    {
    }
};


int main()
{
    int x;
    AnonymousClass(x);
    return 0;
} 
         


        
3条回答
  •  情深已故
    2020-12-19 08:06

    You're missing an actual name for your variable/object:

    AnonymousClass myclass(x);
    

    Instead of that you could as well write...

    AnonymousClass (myclass)(x);
    

    So your line of code results in this:

    AnonymousClass (x);
    

    Or more common:

    AnonymousClass x;
    

    Why it happens? Brackets are just there for logical grouping ("what belongs together?"). The only difference is, they're forced for arguments (i.e. you can't just write AnonymousClass myclass x).

提交回复
热议问题