复制构造函数和默认构造函数 [英] Copy Constructor and default constructor

查看:185
本文介绍了复制构造函数和默认构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我们为类定义一个复制构造函数时,我们必须显式地定义一个默认的构造函数。请说明理由。

Do we have to explicitly define a default constructor when we define a copy constructor for a class?? Please give reasons.

例如:

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??
};      

此外,如果我们为除复制构造函数之外的类定义任何其他参数化构造函数,必须定义默认构造函数??考虑没有复制构造函数的上述代码,并将其替换为

Also, if we define any other parameterized constructor for a class other than the copy constructor, do we also have to define the default constructor?? Consider the above code without the copy constructor and replace it with

A(int z)
{
    z.i = 10;
}

Alrite ....看到答案后,我写了以下程序。 / p>

Alrite....After seeing the answers I wrote the following program.

#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();
}

这个程序似乎没有默认的构造函数工作正常。请解释为什么是这种情况?我真的很混淆的概念.....

ANd this program seems to be working fine without the default constructor. Please explain why is this the case?? I am really confused with the concept.....

推荐答案

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

Yes. Once you explicitly declare absolutely any constructor for a class, the compiler stops providing the implicit default constructor. If you still need the default constructor, you have to explicitly declare and define it yourself.

可以编写一个也是默认构造函数的复制构造函数(或转换构造函数或任何其他构造函数)。如果你的新构造函数属于这个类别,没有必要再提供一个额外的默认构造函数:)

P.S. It is possible to write a copy constructor (or conversion constructor, or any other constructor) that is also default constructor. If your new constructor falls into that category, there's no need to provide an additional default constructor anymore :)

例如:

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

S dummy(0);

S::S(const S& = dummy) {
}


$ b b

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

In the above example the copy constructor is at the same time the default constructor.

这篇关于复制构造函数和默认构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆