简体   繁体   中英

C++ Auto typecast

I was surprised that the compiler automatically casted an Integer to my own defined Class

CCoolClass(long numerator = 0, long denominator = 1);

I did overload the operator + like this

friend CFraction operator + (CCoolClass left, CCoolClass right);

Why does this work and not lead to a compiler error ? Where does the auto-typecast from integer to CCoolClass come from?

CCoolClass a = CCoolClass(2,3) + 3;

I do understand this is cool, but I was rather surprised. Regards

It's because you didn't tell the compiler that your constructor can only be used explicitly. That means it can do implicit type conversions to your class.

To make your constructor explicit, so it can't be used in type conversions like these, you declare it explicit :

explicit CCoolClass(long numerator = 0, long denominator = 1);

It's not a typecast, it's an implicit constructor. Your constructor uses default parameters, so your code becomes:

CCoolClass a = CCoolClass(2,3) + CCoolClass(3);

...which is equivalent to

CCoolClass a = CCoolClass(2,3) + CCoolClass(3,1);

You would have gotten a compilation error if you made your constructor explicit like Joachim's answer (because implicit construction will be disallowed), or if you did not specify any default parameters (because CCoolClass(3) will be invalid).

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