C++中声明explicit转换运算符为何引发类型转换错误?
operator int() const as explicit cause a compilation error when assigning to an int? Question Details
I've implemented bidirectional conversion between CircularInt and int, and marked the conversion operator operator int() const as explicit:
CircularInt(int n): CircularInt(1, 12 , n) { } explicit operator int() const{ return current;};
When executing this code:
CircularInt hour {1, 10 , 7 }; // current = 7 int i = hour;
I hit a compilation error:
error: cannot convert ‘CircularInt’ to ‘int’ in initialization int i = hour;
Removing the explicit keyword fixes everything. Can someone explain why this happens?
Answer
Great question! Let's break down the core of the issue:
The
explicitkeyword, when applied to a conversion operator (likeoperator int()), tells the C++ compiler that this conversion cannot happen automatically (implicitly).Without
explicit, the compiler will silently use youroperator int()to convert theCircularIntobject to anintwhenever it needs to—like when you assignhourtoint i. This is called an implicit conversion, and it happens behind the scenes without you explicitly asking for it.When you add
explicit, you're enforcing that the conversion must be done intentionally and explicitly. That means the compiler won't do it for you in assignments or other contexts where implicit conversions would normally occur. To fix the error, you need to explicitly request the conversion, like this:int i = static_cast<int>(hour);(You could also use a C-style cast like
(int)hour, butstatic_castis the preferred, type-safe C++ approach.)
The point of using explicit here is to prevent accidental implicit conversions that might lead to unexpected behavior. For example, if you had a function that takes an int and accidentally passed a CircularInt instead, explicit would catch that as a compilation error instead of silently converting the object and potentially causing bugs.
内容的提问来源于stack exchange,提问作者Tomer

