Prev: enum operator overload ambiguity
Next: const as default
From: ThosRTanner on 29 Jan 2010 06:47 Why exactly is this allowed? enum Fred { jim, bill, eric } int main() { std::string x; x = jim; return 0; } eliding the constructor and the assignment elicits the expected error. It hardly seems a useful thing to do. It happens on 2 compilers -- [ See http://www.gotw.ca/resources/clcm.htm for info about ] [ comp.lang.c++.moderated. First time posters: Do this! ]
From: Gert-Jan de Vos on 30 Jan 2010 03:13 On Jan 30, 12:47 am, ThosRTanner <ttann...(a)bloomberg.net> wrote: > Why exactly is this allowed? > > enum Fred { jim, bill, eric } > > int main() > { > std::string x; > x = jim; > return 0; > > } A char can be assigned to a string. enum constant to char is an integral conversion. Your example assigns the value of jim (0) as a character to the string x. This needs one implicit integral conversion. -- [ See http://www.gotw.ca/resources/clcm.htm for info about ] [ comp.lang.c++.moderated. First time posters: Do this! ]
From: Bo Persson on 30 Jan 2010 04:22 ThosRTanner wrote: > Why exactly is this allowed? > > enum Fred { jim, bill, eric }; > > int main() > { > std::string x; > x = jim; > return 0; > } > > eliding the constructor and the assignment elicits the expected > error. It hardly seems a useful thing to do. > > It happens on 2 compilers It isn't exactly designed this way, but it just happens to work according to the standard. :-( The std::string class has an assignment operator for a single char, allowing you to write x = 'a'; Now, char is an integer type and enums are implicitly convertible to integer types. Blame it on C compatibility! :-) Bo Persson -- [ See http://www.gotw.ca/resources/clcm.htm for info about ] [ comp.lang.c++.moderated. First time posters: Do this! ]
|
Pages: 1 Prev: enum operator overload ambiguity Next: const as default |