问题描述
考虑一个类层次结构,其中 A
是基类, B
派生自 A
。
Consider a class hierarchy where A
is the base class and B
derives from A
.
如果复制构造函数未在 B
中定义,一。调用时,此复制构造函数将调用基类复制构造函数(即使是合成的,如果用户没有提供)。
If the copy constructor is not defined in B
, the compiler will synthesize one. When invoked, this copy constructor will call the base class copy constructor (even the synthesized one, if none has been provided by the user).
#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
如果用户在<$ c $中定义了自己的复制构造函数c> B ,当被调用时,这个拷贝构造函数将调用基类默认构造函数,除非显式地出现对基类拷贝构造函数的调用)。
If the user defines its own copy constructor in B
, when invoked, this copy constructor will call the base class default constructor, unless a call to the base class copy constructor is explicitly present (e.g. in the initialization list).
#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
为什么用户定义的复制构造函数不调用基类复制构造函数作为默认行为?
My question is, why doesn't the user defined copy constructor call the base class copy constructor as a default behavior?
推荐答案
隐式拷贝构造函数被定义(它不会有意义调用默认)。一旦定义任何构造函数(复制或其他),它的正常自动行为就是调用默认的父构造函数,因此对于一个特定的用户定义构造函数,它将不一致。
That's just the way the implicit copy constructor is defined (it wouldn't make sense calling the default). As soon as you define any constructor (copy or otherwise) its normal automatic behavior is to call the default parent constructor, so it would be inconsistent to change that for one specific user-defined constructor.
这篇关于为什么隐式复制构造函数调用基类复制构造函数和定义的复制构造函数不?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!