Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/151.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++ - Fatal编程技术网

复制构造函数是否调用默认构造函数来创建对象 在C++中创建对象时,复制构造函数调用默认构造函数吗?如果我隐藏默认构造函数,我应该仍然能够创建副本,对吗?

复制构造函数是否调用默认构造函数来创建对象 在C++中创建对象时,复制构造函数调用默认构造函数吗?如果我隐藏默认构造函数,我应该仍然能够创建副本,对吗?,c++,C++,删除默认构造函数不会阻止您复制对象。当然,首先需要一种生成对象的方法,即需要提供一个非默认构造函数 struct Demo { Demo() = delete; Demo(int _x) : x(_x) { cout << "one-arg constructor" << endl; } int x; }; int main() { Demo a(5); // Create the original using one-arg const

删除默认构造函数不会阻止您复制对象。当然,首先需要一种生成对象的方法,即需要提供一个非默认构造函数

struct Demo {
    Demo() = delete;
    Demo(int _x) : x(_x) { cout << "one-arg constructor" << endl; }
    int x;
};

int main() {
    Demo a(5); // Create the original using one-arg constructor
    Demo b(a); // Make a copy using the default copy constructor
    return 0;
}
struct演示{
Demo()=删除;
Demo(int_x):x(x){cout答案是否定的

通过
new
指令创建对象内存。 然后,复制构造函数负责实际的复制(显然,只有当它不是浅拷贝时才相关)

如果需要,可以在复制构造函数执行之前显式调用其他构造函数

您可以通过复制/粘贴此代码并运行它来轻松地测试它

#include <stdio.h>

class Ctest
{
public:

    Ctest()
    {
        printf("default constructor");
    }

    Ctest(const Ctest& input)
    {
        printf("Copy Constructor");
    }
};


int main()
{    
    Ctest *a = new Ctest();     //<-- This should call the default constructor

    Ctest *b = new Ctest(*a);  //<-- this will NOT call the default constructor
}
#包括
类别测试
{
公众:
Ctest()
{
printf(“默认构造函数”);
}
测试(常数测试和输入)
{
printf(“复制构造函数”);
}
};
int main()
{    

cTest**新的CtTest.(;)/不清楚你有什么“默认构造函数”。当你的代码没有它们时,C++会提供默认构造函数,而你没有指定一个显式的<代码>删除>代码>。然后还有无参数的构造器,也被称为“默认”。,但您的类不需要有其中一个。不管我的问题是什么。这两个都是默认的,我不关心它是编译器生成的还是程序员定义的。
#include <stdio.h>

class Ctest
{
public:

    Ctest()
    {
        printf("default constructor");
    }

    Ctest(const Ctest& input)
    {
        printf("Copy Constructor");
    }
};


int main()
{    
    Ctest *a = new Ctest();     //<-- This should call the default constructor

    Ctest *b = new Ctest(*a);  //<-- this will NOT call the default constructor
}