问题
I have a base class A and it has a subclass B. A overrides the + operator and B overrides it as well,calls the parent's +operator, and casts the result to B. Then I am getting the error message:
error C2440: '' : cannot convert from 'A' to 'B'
I thought polymorphism worked in a way that should allow this to work?
回答1:
In polymorphism you cannot convert A
to B
, you can convert B
to A
. B is a kind of A, but A is NOT a kind of B.
For example, in the classic Shape classes. If you have a class Shape
and a class Rectangle
that extends [inherit from] Shape
, you cannot convert a Shape
instance to Rectangle
, but you CAN cast a Rectangle
to Shape
, because it is a 'kind of' Shape.
来源:https://stackoverflow.com/questions/7614313/cerror-c2440-function-style-cast-cannot-convert-from-atype-to-bt