User-defined conversion operator from base class

前端 未结 11 1563
南旧
南旧 2020-12-01 02:40

Introduction

I am aware that \"user-defined conversions to or from a base class are not allowed\". MSDN gives, as an explanation to this rule, \"You

11条回答
  •  眼角桃花
    2020-12-01 03:19

    It is an old discussion, though, but I just wanted to add some experiences of my own.

    In a class library, we had once mathematical objects like 2D points AND 2D vectors. Because the features of the objects of both classes are mostly the same (although not quite the same, wherefore both classes were needed), the idea was to define a Vector2D and to derive Point2D from it. It would spare a lot of repeating definitions, but a custom conversion operator from vector to point would not be possible.

    So since we strongly wanted to deliberately exchange the types in the code, we just decided to give up the idea of derivation, declared both classes independently and introduced implicit conversion operators. Then we could freely exchange both types in the code.

提交回复
热议问题