c ++:error C2440:'< function-style-cast>' :不能从'A< TYPE>'到'B< TYPE>

c ++:error C2440:'< function-style-cast>' :不能从'A< TYPE>'到'B< TYPE>

问题描述:

我有一个基类A,它有一个子类B.
覆盖+操作符,B也覆盖它,调用父类的+操作符,并将结果转换为B.然后我得到错误讯息:

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:


错误C2440:'':无法将'A'
转换为'B'

error C2440: '' : cannot convert from 'A' to 'B'

我认为多态性的工作方式应该允许这个工作?

I thought polymorphism worked in a way that should allow this to work?

在多态性中,您不能将 A 转换为 B ,可以转换 B A 。 B是一种A,但A不是B的一种。

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.

例如,在经典的Shape类中。如果你有一个类 Shape 和一个类 Rectangle extends [inherit from] Shape ,您不能将 Shape 实例转换为 Rectangle ,但是您可以转换 Rectangle Shape ,因为它是一种形状。

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.