What's actually going on in this AnonymousClass(variable) declaration?
Trying to compile:
class AnonymousClass
{
public:
AnonymousClass(int x)
{
}
};
int main()
{
int x;
AnonymousClass(x);
return 0;
}
generates errors from MSVC:
foo.cpp(13) : error C2371:开发者_JS百科 'x' : redefinition; different basic types
foo.cpp(12) : see declaration of 'x'
foo.cpp(13) : error C2512: 'AnonymousClass' : no appropriate default constructor available
g++'s error messages are similar:
foo.cpp: In function ‘int main()’:
foo.cpp:13: error: conflicting declaration ‘AnonymousClass x’
foo.cpp:12: error: ‘x’ has a previous declaration as ‘int x’
foo.cpp:12: warning: unused variable ‘x’
It's easily fixable by giving the AnonymousClass
object an explicit name, but what's going on here and why? I presume that this is more declaration syntax weirdness (like the cases described in Q10.2 and Q10.21 of the comp.lang.C++ FAQ), but I'm not familiar with this one.
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
.
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
).
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!
精彩评论