简体   繁体   中英

Why doesn't C++ like this syntax for strings?

name_abbreviation = name_last.resize(2);

Here I have to assign first

name_abbreviation = name_last;

Then

name_abbreviation.resize(2);

Would like to kindly ask you if you could explain me why the other way doesn't work?

Because due to operator precedence this code:

name_abbreviation = name_last.resize(2);

is equal to:

name_abbreviation = (name_last.resize(2));

and is logically equal to:

auto tmp = name_last.resize(2);
name_abbreviation = tmp;

which is not compilable as std::string::resize() returns nothing and even if it would compile it would not do what you want.

What you want to do can be achieved by:

(name_abbreviation = name_last).resize(2);

but this not quite readable code. I, personally, would prefer 2 separate statements.

Note the same result can be achieved by much simpler code:

name_abbreviation = name_last.substr( 0, 2 );

which can be also more efficient on some implementations.

resize() function doesn't return a thing. It changes the size of allocated memory of the string it use on it. So to assign a string to another just use

name_abbreviation = name_last;

using the operator = will make the string on the LHS have the same size of the string on the right and have the same characters..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM