This may be a silly question about inheritance, but it does not make much sense on why I am not allowed to do this. The base class I am inheriting fro开发者_JAVA百科m is std::string
:
class A : public std::string
When I use class A
, I want to do this:
A text;
std::string str = "hello";
text = str;
The compiler complains that there is no binary operator =
to do this.
The reason I want to inherit from string is to add some extra functionality but not lost the functionality std::string
gives by default.
Is there a reason why a base class cannot be automatically assigned to a sub class?
Thanks.
You cannot inherit assignment operators, they are given special treatment. You can use using
to bring them up from the base class.
Also, it's horrendously bad to inherit from Standard-provided classes, except iostream.
Is there a reason why a base class cannot be automatically assigned to a sub class?
Yes. It is because the base class is not a subclass. You can only assign the other way around: assigning a subclass instance to a base class instance would be fine since the subclass is-a base class.
This is the general rule; the other answer explains what's specifically wrong in case of std::string
.
精彩评论