type conversion - Calling unexisting constructor in C++ -
suppose have class string:
class string { public: string (int n); string(const char *p); }
what happen if try:
string mystring='x';
here written char 'x' converted int , call string(int) constructor. however, not understand it.
first, how 'x' can converted int? can imagine "3"
converted 3
"x" converted to? second, have 2 constructors in class. first constructor takes 1 argument of int type , constructor takes pointer char variable argument. try call not existing constructor takes char argument. so, convert char integer, why not try convert char pointer char , use second constructor?
first, how 'x' can converted int? can imagine "3" converted 3 "x" converted to?
don't make mistake of confusing 'x'
, "x"
.
"x"
string literal and, you're right, meaningless try convertint
;'x'
character literal, number (equal underlying value of whatever characterx
maps in basic source character set; ascii,120
); converting integer trivial.
so, convert char integer, why not try convert char pointer char , use second constructor?
there rules in c++ govern "best match". in case, it's int
overload. in case both equal match, compiler present "ambiguous overload" error , forced convert 'x'
explicitly (i.e. manually, cast) in order dictate wanted.
in case not problem, since non-pointers cannot convert pointers.
Comments
Post a Comment