Eri*_*ric 0 c++ inheritance copy
根据我的理解,当创建派生类的对象时,基类构造函数会自动调用(如果存在没有参数的构造函数)。复制构造函数似乎不是这种情况:
#include <iostream>
class Base
{
public:
Base()
{
std::cout << "Base Constructor called" << std::endl;
}
Base(const Base& ref)
{
std::cout << "Base Copy Constructor called" << std::endl;
}
};
class Derived : Base
{
public:
Derived()
{
std::cout << "Derived Constructor called" << std::endl;
}
Derived(const Derived& ref) //: Base(ref) // <- without this Base copy constructor doesnt get called
{
std::cout << "Derived Copy Constructor called" << std::endl;
}
};
int main()
{
Derived d1;
Derived d2 = d1;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
没有 ": Base(ref)" 的输出:
Base Constructor 称为 Derived Constructor Base Constructor 称为 Derived Copy Constructor
带有“:Base(ref)”的输出:
Base Constructor 称为 Derived Constructor Base Copy Constructor 称为 Derived Copy Constructor
因此,除非您显式调用 Base 类复制构造函数,否则将创建新的 Base 类对象而不是复制构造。所以我想只有派生类成员才能实际复制构造,而所有基类成员都将由基类构造函数新创建。现在对我来说,这似乎是你从未真正想要的东西。如果您复制构造一个对象,您希望所有成员都被复制,而不仅仅是其中的一部分。
为什么复制构造函数在这方面与普通构造函数不同?