简体   繁体   中英

Can a constructor be added to an included class?

I am using a library that has some useful types but they are missing some functionality. I am thus thinking if there is a good way to extend these types.

I have taken some other types from the library, inherited from them and just used my own expanded versions. I can't think of a way to make this work for the following issue.

There is a floating point and an integral 2D point struct, ie Point2D and Point2DInt. I would like to be able to either implicitly convert between the two or be able to construct one from the other, in either case I want to add a constructor to this external class.

There is a float to int constructor in the integral class but none that goes the other way.

I understand that I could just make a utility function to do this but would like to know if this is possible in general.

The only way of making a class implicitly convertible to another is to modify one of the classes (either add converting constructor to one, or conversion operator to another). The modification has to be in the definition of the class; not after the definition.

Indeed, you can write a function that takes one as an argument and returns the other, but the implicit conversion is not possible.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM