复制基类和派生类中的构造函数
copy constructor in base and derived class
我不明白两件事:
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
赋值运算符。
相关文章:
- 如何委托派生类使用其父构造函数?
- 如果基类包含双指针成员,则派生类的构造函数
- C++:为什么无法在派生类中访问受保护的构造函数?
- C++派生的类构造函数
- 添加自定义析构函数时,Move 构造函数在派生类中消失
- 在没有默认构造函数的情况下创建的派生对象
- 派生类(构造函数具有参数)和基类(构造函数缺少参数)之间没有可行的转换
- 如何在派生构造函数中多次构造基类
- C++(控制台)构造函数和派生类
- 为什么为派生类定义复制构造函数需要定义基类的默认构造函数?
- 在dynamic_pointer_cast后调用派生类的构造函数
- 如何使用函数(而不是构造函数)将派生类对象分配给基类指针
- 将派生类的构造函数声明为父类的友元
- 如何为具有私有成员的派生类实现移动构造函数
- 使用回调函数从构造函数调用虚拟/派生方法的替代方法?
- 在派生自线程类的构造函数中传递字符串
- C++ 为什么要将对基类的引用传递给派生类的构造函数
- C++将派生类的const值传递给基意外行为的构造函数
- 在模板派生类中继承具有类型别名的构造函数
- 正在调用基方法,而不是从构造函数派生方法