复制构造函数和默认构造函数

Lig*_*dle 14 c++ constructor copy

在为类定义复制构造函数时,是否必须显式定义默认构造函数?请说明原因.

例如:

class A 
{
    int i;

    public:
           A(A& a)
           {
               i = a.i; //Ok this is corrected....
           }

           A() { } //Is this required if we write the above copy constructor??
};      
Run Code Online (Sandbox Code Playgroud)

另外,如果我们为复制构造函数以外的类定义任何其他参数化构造函数,我们是否还必须定义默认构造函数?考虑上面没有复制构造函数的代码并替换它

A(int z)
{
    z.i = 10;
}
Run Code Online (Sandbox Code Playgroud)

Alrite ....看到答案后,我写了下面的程序.

#include <iostream>

using namespace std;

class X
{
    int i;

    public:
            //X();
            X(int ii);
            void print();
};

//X::X() { }

X::X(int ii)
{
    i = ii;
}


void X::print()
{
    cout<<"i = "<<i<<endl;
}

int main(void)
{
    X x(10);
  //X x1;
    x.print();
  //x1.print();
}
Run Code Online (Sandbox Code Playgroud)

如果没有默认构造函数,这个程序似乎工作正常.请解释为什么会这样?我真的很困惑这个概念......

AnT*_*AnT 33

是.一旦明确声明了类的任何构造函数,编译器就会停止提供隐式默认构造函数.如果您仍然需要默认构造函数,则必须自己显式声明和定义它.

PS可以编写也是默认构造函数的复制构造函数(或转换构造函数或任何其他构造函数).如果您的新构造函数属于该类别,则无需再提供其他默认构造函数:)

例如:

// Just a sketch of one possible technique    
struct S {
  S(const S&);
  S(int) {}
};

S dummy(0);

S::S(const S& = dummy) {
}
Run Code Online (Sandbox Code Playgroud)

在上面的示例中,复制构造函数同时是默认构造函数.

  • 您也可以使用*only*复制构造函数,同时提供默认构造函数:`struct X {static X x; X(X const&= x){}}; XX :: x;`:) (2认同)