Β§ 12.3.1 / 1 "Type conversions of class objects can be specified by constructors and conversion functions. These conversions are called user conversions and are used for implicit type conversions (Section 4) for initialization (8.5), and for explicit type conversions (5.4, 5.2. 9).
Yes, we can do conversions, but only if one or both sides are a user-defined type, so we cannot do one for double
to int
.
struct demostruct { demostruct(int x) :data(x) {} //used for conversions from int to demostruct operator int() {return data;} //used for conversions from demostruct to int int data; }; int main(int argc, char** argv) { demostruct ds = argc; //conversion from int to demostruct return ds; //conversion from demostruct to int }
As Rob out pointed out, you can add the explicit
keyword to any of these conversion functions, which requires the user to explicitly use them with (demostruct)argc
or (int)ds
, as in your code, instead of implicitly converting them. If you convert to the same type, it is usually better to have one or both as explicit
, otherwise you may get compilation errors.
source share