相关疑难解决方法(0)

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

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

例如:

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)
{ …
Run Code Online (Sandbox Code Playgroud)

c++ constructor copy

14
推荐指数
1
解决办法
2万
查看次数

标签 统计

c++ ×1

constructor ×1

copy ×1