考虑一个类层次结构,其中A是基类并B派生自A.
如果未定义复制构造函数B,编译器将合成一个.调用时,此复制构造函数将调用基类复制构造函数(即使是合成的构造函数,如果用户没有提供).
#include <iostream>
class A {
int a;
public:
A() {
std::cout << "A::Default constructor" << std::endl;
}
A(const A& rhs) {
std::cout << "A::Copy constructor" << std::endl;
}
};
class B : public A {
int b;
public:
B() {
std::cout << "B::Default constructor" << std::endl;
}
};
int main(int argc, const char *argv[])
{
std::cout << "Creating B" << std::endl;
B b1;
std::cout << "Creating …Run Code Online (Sandbox Code Playgroud) 就像在标题中一样,如何从派生类复制构造函数中调用基类复制构造函数?
根据我的理解,当创建派生类的对象时,基类构造函数会自动调用(如果存在没有参数的构造函数)。复制构造函数似乎不是这种情况:
#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 …Run Code Online (Sandbox Code Playgroud)