假设我有一个基类Person,我公开Teacher从基类继承一个类Person.现在在main函数中我写了这样的东西
// name will be passed to the base class constructor and 17
// is for derived class constructor.
Teacher object(“name”,17) ;
Teacher object1=object; //call to copy constructor
Run Code Online (Sandbox Code Playgroud)
现在我还没有为这两个类编写复制构造函数,当然会调用默认的复制构造函数.Person类的默认复制构造函数将首先调用基类的复制构造函数.
现在问题是假设我只为基类编写复制构造函数,会发生什么,派生类的默认复制构造函数将调用我的书写复制构造函数.
现在假设我为这两个类编写了复制构造函数.现在派生类(即教师)的复制构造函数将调用基类的默认构造函数而不是复制构造函数为什么?
只有派生类的默认复制构造函数可以自动调用基类的复制构造函数吗?
您必须显式调用基本复制构造函数:
Teacher(const Teacher& other)
: Person(other) // <--- call Person's copy constructor.
, num_(other.num_)
{
}
Run Code Online (Sandbox Code Playgroud)
否则Person将调用默认构造函数.
默认情况下,所有用户定义的构造函数都调用其基类的默认构造函数(除非它们显式调用不同的构造函数),如果基类的默认构造函数是用户定义的或编译器生成的,则无关紧要.
当编译器生成复制构造函数时,它将调用基类的复制构造函数.
编译器定义的构造函数不是特殊的,可以显式调用它们:
class Base {
int num_
public:
Base(int n) : num_(n) { }
// copy constructor defined by compiler
};
class Derived : public Base {
float flt_;
public:
Derived(float f, int n) : Base(n), flt_(f) { }
// Copy constructor
Derived(const Derived& other)
: Base(other) // OK to explicitly call compiler generated copy constructor
, flt_(other.flt_)
{
}
};
Run Code Online (Sandbox Code Playgroud)
有关更多详细信息,请参阅此Wikipedia文章.