简体   繁体   English

默认构造函数C ++

[英]Default constructor c++

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 要求A的默认构造函数

Argument constructor called for A 参数构造函数要求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? 因此,对于最后一个,有另一个调用的构造函数,我的问题是在这种情况下n具有哪种类型和哪种类型?

 A n();

declares a function, named n , that takes no arguments and returns an A . 声明一个名为n的函数,该函数不带任何参数并返回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 . 因为没有定义函数n

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). 语言标准规定始终要解决模糊性,而要使用函数声明(第8.5.8节)。

So n is a function without arguments returning an A . 因此n是一个不带参数返回A的函数。

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. 您要做的只是告诉(声明)编译器,这里有一个函数n返回A并且不带参数。

No there is not a different constructor. 不,没有其他构造函数。

A n();

is treated as a declaration of function taking no arguments and returning A object. 被视为不带参数并返回A对象的函数声明。 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()' main.cpp:129:错误:请求'n'中的成员'x',这是非类类型'A()'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM