Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/133.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
默认构造器C++_C++_Constructor_Default Constructor_Most Vexing Parse - Fatal编程技术网

默认构造器C++

默认构造器C++,c++,constructor,default-constructor,most-vexing-parse,C++,Constructor,Default Constructor,Most Vexing Parse,我试图理解如果您不编写默认构造函数,那么编译器提供的默认构造函数与您自己的默认构造函数相比是如何工作的 例如,我写了一个简单的类: class A { private: int x; public: A() { std::cout << "Default constructor called for A\n"; } A(int x) { std::cout << "Ar

我试图理解如果您不编写默认构造函数,那么编译器提供的默认构造函数与您自己的默认构造函数相比是如何工作的

例如,我写了一个简单的类:

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;
}
输出为:

默认构造函数调用了一个

参数构造函数调用了一个

对于最后一个,有另一个构造函数被调用,我的问题是,在这种情况下,n有哪一个,哪一种类型

声明一个名为n的函数,该函数不接受任何参数并返回a

因为它是一个声明,所以不会调用/执行任何代码,尤其是没有构造函数

A n();
在那个声明之后,你可以写一些

A myA = n();
这将编译。但它不会链接!因为函数n没有定义

可以解析为具有空初始值设定项或函数声明的对象定义

语言标准规定,歧义的解决始终有利于功能声明§8.5.8


因此,n是一个没有参数的函数,对于最后一个未调用构造函数的函数,它返回a.


因此,甚至不会生成任何代码。你所做的只是告诉编译器有一个函数n,它返回a,不带参数。

不,没有其他构造函数

A n();
被视为不带参数并返回对象的函数声明。您可以通过以下代码看到这一点:

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;
}
错误是:


main.cpp:129:错误:请求“n”中的成员“x”,这是非类类型的“A”

google最令人烦恼的解析这本身并不是一个错误,但如果您试图通过n访问A的方法,它将是错误的。
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;
}