复制基类和派生类中的构造函数

copy constructor in base and derived class

本文关键字:构造函数 派生 基类 复制      更新时间:2023-10-16

我不明白两件事:

1-在定义对象d2的代码1中,调用基类的默认构造函数和派生类的复制构造函数。但在代码2中(派生类没有复制构造函数),只调用基类的复制构造函数!

为什么要复制基类的构造函数?是否调用了派生类的构造函数?

2-之间有什么区别

D d2 = d1 ; 

D d2;
d2 = d1;

在这个例子中?这是什么原因?

代码1

//code 1
#include <iostream> 

using std::cout;
using std::endl;
///////////////////////////
class B
{
protected:
int x;
public:
B()
{
x = 4;
cout << "default constructor of Base class " << endl;
}
B(int a)
{
x = a;
cout << "parametric constructor of Base class" << endl;
}
B(const B &b)
{
x = b.x;
cout << "copy constructor of Base class " << endl;
}
};
////////////////////////////////////////////////////////////
class D : public B
{
private:
int y;
public:
D()
{
y = 5;
cout << "default constructor of Derived class" << endl;
}
D(int k)
{
y = k;
cout << "parametric constructor of Derived class" << endl;
}
D(D& copy)
{
cout << "copy constructor of Derived class" << endl;
}

};
////////////////////////////////////////////////////////////
int main()
{
D d1(3);
D d2 = d1;
return 0;
}

代码2

//code 2
#include <iostream> 

using std::cout;
using std::endl;
///////////////////////////
class B
{
protected:
int x;
public:
B()
{
x = 4;
cout << "default constructor of Base class " << endl;
}
B(int a)
{
x = a;
cout << "parametric constructor of Base class" << endl;
}
B(const B &b)
{
x = b.x;
cout << "copy constructor of Base class " << endl;
}
};
////////////////////////////////////////////////////////////
class D : public B
{
private:
int y;
public:
D()
{
y = 5;
cout << "default constructor of Derived class" << endl;
}
D(int k)
{
y = k;
cout << "parametric constructor of Derived class" << endl;
}
/*     D(D& copy)
{
cout << "copy constructor of Derived class" << endl;
}
*/     
};
////////////////////////////////////////////////////////////
int main()
{
D d1(3);
D d2 = d1;
return 0;
}

问题1

在";代码1;您已经为派生类定义了一个复制构造函数。因此,编译器不再为您创建一个。由于在字段初始化列表中没有专门调用基构造函数,因此在派生类复制构造函数中,它所做的第一件事就是调用基类默认构造函数。

然而,在";代码2;由于不再为派生类定义复制构造函数,因此编译器会隐式为您创建一个复制构造函数。请参阅此问题。最上面的答案解释了将调用基本副本构造函数。

问题2

从这个链接:

无论何时从同一类型的另一个对象初始化对象(通过直接初始化或复制初始化),都会调用复制构造函数(除非重载解析选择了更好的匹配或取消了调用),其中包括

  • 初始化:T a=b;或T a(b);,其中b为T型

因此D d2 = d1;调用D复制构造函数,而D d2; d2 = d1;调用D默认构造函数,然后调用D赋值运算符。