我对用于实例化对象的不同语法感到困惑。
这是我的课:
class Object
{
private:
int field = 0;
public:
Object() = default; // Just for testing.
~Object() = default; // Just for testing.
Object( const Object& obj ) = default; // Just for testing.
};
这是主要方法:
int main()
{
Object b(); // ???
Object c{}; // default
Object d = Object(); // default
Object e = Object{}; // default
Object f ( Object() ); // ???
Object g { Object() }; // default
Object a; // default but avoid
Object h ( Object() ); // ???
Object i { Object{} }; // default
Object j = i; // copy
Object k( j ); // copy
Object l{ k }; // copy
Object m = { l }; // copy
Object n = ( m ); // copy
auto o = Object(); // default
auto p = Object{}; // default
return 0;
}
I have no problem with the one's marked default
or copy
. I just want to know, which constructor is called for the one's with ???
as the default one is not called. Has it something to do with ()
initialization, as it can be seen.
我知道这可能并不重要,但我对此表示怀疑。
谁能帮忙!
这三个声明都是函数声明。
Object b();
declares a function namedb
, which takes nothing and returnsObject
.Object f ( Object() );
declares a function namedf
, which takes a unnamed parameter whose type is a function returningObject
and taking nothing (i.e.Object()
), and returnsObject
. Similarly forObject h ( Object() );
.实际上,它没有调用任何构造函数。
当您更改Object类以使所有字段都是公共的(以便您可以查看它们)时:
然后尝试在main方法中调用空括号:
You get an error because
b
is not an Object but a function:错误:请求“ b”中的成员“ field”,该成员属于非类类型“ Object()”
这就是为什么当您要调用空括号构造函数时,必须在不带任何括号的情况下调用它: