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

后端 未结 3 923
死守一世寂寞
死守一世寂寞 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).

    0 讨论(0)
  • 2020-12-19 08:14
    AnonymousClass(x);
    

    It defines a variable x of type AnonymousClass. That is why you're getting redefinition error, because x is already declared as int.

    The parentheses are superfluous. You can add even more braces like:

    AnonymousClass(x);
    AnonymousClass((x));
    AnonymousClass(((x)));
    AnonymousClass((((x))));
    //and so on
    

    All of them are same as:

    AnonymousClass x;
    

    Demo: http://www.ideone.com/QnRKH


    You can use the syntax A(x) to create anonymous object, especially when calling a function:

    int x = 10;
    f(A(x));        //1 - () is needed
    f(A((((x)))));  //2 - extra () are superfluous
    

    Both line 1 and 2 call a function f passing an object of type A :

    • http://www.ideone.com/ofbpR

    But again, the extra parentheses are still superfluous at line 2.

    0 讨论(0)
  • 2020-12-19 08:26

    To avoid such a mistake, just remember one rule: If you declare an anonymous object with one argument, just place it into a pair of parentheses!

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