考虑以下代码:
#include <iostream>
struct A
{
A() {} // Can't be commented
A( const A& other ) =delete;
int i;
};
struct B : public A
{
B( int j ) { this->i = j; }
B( const B& other ) { this->i = other.i; }
};
int main()
{
B b(42);
std::cout << b.i << std::endl;
}
如果注释A的空构造函数,为什么不能编译此代码?我以为A总是有一个默认的构造函数,当我禁用其复制构造函数时会发生什么变化?
如果您声明了至少一个非默认构造函数,则编译器将不会为您生成一个默认构造函数。如果您想一想,这实际上是有道理的。想象一下一个可以创建的类,而无需将某些值传递给构造函数。在这种情况下,无论您尝试多少,都将无法创建空的构造函数。
当您注释掉A的空构造函数时,B的构造函数将无法调用它。
当您注释掉两个构造函数时,编译器都认为可以为副本和空构造函数生成默认实现。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句