假设我有一个类A,它提供了一个复制构造函数(接受另一个A)。
然后,我有了A的派生类B,它不提供副本构造函数。
是否可以像非复制构造函数那样将A的复制构造函数继承到B中?
注意:除了A中包含的状态外,B没有任何状态。
如果除了基类的copy构造函数所提供的功能之外不需要其他特殊行为,则只需告诉编译器使用默认的copy构造函数即可,它将调用基类的copy构造函数,这样就可以了。
#include <iostream>
class A {
public:
int a;
A()=default;
A(const A& other) {
std::cout << "Class A copy constructor called" << std::endl;
a = other.a;
}
};
class B: public A {
public :
int b;
B() = default;
B(const B& other) = default;
};
int main() {
B b1;
b1.a = 1;
b1.b = 2;
B b2(b1);
std::cout << b2.a << " - " << b2.b << std::endl;
}
输出:
Class A copy constructor called
1 - 2
编辑:
为了回答您的确切问题:我相信using指令使所有基类构造函数在派生类中可见。我个人不太喜欢这种行为,所以我更喜欢使用默认构造函数而不是using
指令,但这就是我。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句