考虑一个类层次结构,其中
如果在
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 B by copy" << std::endl;
B b2(b1);
return 0;
}
输出:
Creating B
A::Default constructor
B::Default constructor
Creating B by copy
A::Copy constructor
如果用户在类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;
}
B(const B& rhs) {
std::cout << "B::Copy constructor" << std::endl;
}
};
int main(int argc, const char *argv[])
{
std::cout << "Creating B" << std::endl;
B b1;
std::cout << "Creating B by copy" << std::endl;
B b2(b1);
return 0;
}
输出:
Creating B
A::Default constructor
B::Default constructor
Creating B by copy
A::Default constructor
B::Copy constructor
我的问题是,为什么用户定义的复制构造函数不会默认调用基类的复制构造函数?