If you do not declare copy-assignment operator in a class, the compiler will declare one for you implicitly. The implicitly declared copy-assignment operator will hide any inherited assignment operators (read about "name hiding" in C++), meaning that any inherited assignment operators will become "invisible" to the unqualified name lookup process (which is what happens when you do b = c
), unless you take specific steps to "unhide" them.
In your case, class B
has no explicitly declared copy-assignment operator. Which mean that the compiler will declare
B& B::operator =(const B&)
implicitly. It will hide the operator inherited from A
. The line
b = c;
does not compile, because, the only candidate here is the above implicitly declared B::operator =
(the compiler told you about that already); all other candidates are hidden. And since c
is not convertible to B&
, the above assignment does not compile.
If you want your code to compile, you can use using-declaration to unhide the inherited A::operator =
by adding
using A::operator =;
to the definition of class B
. The code will now compile, although it won't be a good style. You have to keep in mind that in this case the b = c
assignment will invoke A::operator =
, which assigns only the A
portions of the objects involved. (But apparently that is your intent.)
Alternatively, in cases like this you can always work around name hiding by using a qualified version of the name
b.A::operator =(c);
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…