C ++对象实例化-使用空括号实例化对象时调用哪个构造函数

我对用于实例化对象的不同语法感到困惑。

这是我的课:

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 named b, which takes nothing and returns Object.

Object f ( Object() ); declares a function named f, which takes a unnamed parameter whose type is a function returning Object and taking nothing (i.e. Object()), and returns Object. Similarly for Object h ( Object() );.

点赞
评论
呤!!
呤!!

实际上,它没有调用任何构造函数。

当您更改Object类以使所有字段都是公共的(以便您可以查看它们)时:

#include <iostream>
class Object
{
public:
    int field = 0;
    Object() = default;
    ~Object() = default;
    Object( const Object& obj ) = default;
};

然后尝试在main方法中调用空括号:

int main()
{
    Object b();
    std::cout << b.field << '\n';
    return 0;
}

You get an error because b is not an Object but a function:

错误:请求“ b”中的成员“ field”,该成员属于非类类型“ Object()”

这就是为什么当您要调用空括号构造函数时,必须在不带任何括号的情况下调用它:

int main()
{
    Object b;    // this is correct
    std::cout << b.field << '\n';
    return 0;
}
点赞
评论