Default constructor c++

泄露秘密 提交于 2019-12-19 04:22:00

问题


I am trying to understand how default constructor (provided by the compiler if you do not write one) versus your own default constructor works.

So for example I wrote this simple class:

class A
{
    private:
        int x;
    public:
        A() { std::cout << "Default constructor called for A\n"; }
        A(int x)
        {
            std::cout << "Argument constructor called for A\n";
            this->x = x;
        }
};

int main (int argc, char const *argv[])
{
    A m;
    A p(0);
    A n();

    return 0;
}

The output is :

Default constructor called for A

Argument constructor called for A

So for the last one there is another constructor called and my question is which one and which type does n have in this case?


回答1:


 A n();

declares a function, named n, that takes no arguments and returns an A.

Since it is a declaration, no code is invoked/executed (especially no constructor).

After that declaration, you might write something like

A myA = n();

This would compile. But it would not link! Because there is no definition of the function n.




回答2:


A n();

could be parsed as an object definition with an empty initializer or a function declaration.

The language standard specifies that the ambiguity is always resolved in favour of the function declaration (§8.5.8).

So n is a function without arguments returning an A.




回答3:


For the last one NO constructor gets called.

For that matter no code even gets generated. All you're doing is telling (declaring) the compiler that there's a function n which returns A and takes no argument.




回答4:


No there is not a different constructor.

A n();

is treated as a declaration of function taking no arguments and returning A object. You can see this with this code:

class A
{
public:
    int x;

public:

    A(){ std::cout << "Default constructor called for A\n";}

    A(int x){

        std::cout << "Argument constructor called for A\n";

        this->x = x;

    }
};


int main(int argc, char const *argv[])
{

    A m;
    A p(0);
    A n();
    n.x =3;

    return 0;
}

The error is:

main.cpp:129: error: request for member ‘x’ in ‘n’, which is of non-class type ‘A()’



来源:https://stackoverflow.com/questions/22835517/default-constructor-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!