[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Re: assign to std::string from int causes NO ERROR



On Wed, Jun 11, 2003 at 05:31:58PM -0300, amaschio@reckon.com.br wrote:
>   //string z=2;  // OK: does NOT compile

Note that although you write '=' here, you are still constructing a new
string object.  There is no basic_string constructor which takes an integer,
so it does not compile.

>   x[key] = 2;    // BUG???: compiles OK

Here, you are assigning 2 to an existing string object.  There is an
overloaded assignment operator:

    basic_string&  operator= (char c);

This member function is the one being used.  The number 2 is being converted
to a char; the actual character is whatever 2 is in the ASCII chart.

As an experiment, try assigning "x[key] = 65;" instead.  Then retrieve that
string and print it via *c*haracter *out*put:

    std::cout << x[key] << std::endl;

You will see a capital 'A' printed.


Phil

-- 
If ye love wealth greater than liberty, the tranquility of servitude greater
than the animating contest for freedom, go home and leave us in peace.  We seek
not your counsel, nor your arms.  Crouch down and lick the hand that feeds you;
and may posterity forget that ye were our countrymen.            - Samuel Adams



Reply to: