Use a constructor initialization list, so the member a
is initialized via the copy constructor:
B(const A&a):a(a){}
If you don't use a constructor initialization list, then the compiler first tries to initialize A a;
, and only after assigns the other a
to it. However, the first initialization fails because there is no default constructor provided. In general, it is recommended to always using the constructor initialization list when initializing members. In this way, instead of calling one constructor + one assignment operator, you only call the copy constructor.
I suggest changing the name of the member from a
to e.g. _a
, so the code becomes a bit more clear.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…