Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Issue with string::operator+=

Tags:

c++

string

I tried to append two letters to a string, but it seems that the string is not changed:

void fun()
{
    string str;
    str += 'a' + 'b';

    cout << str;
}

I checked the source code of STL and found the implementation of operator+=, but I still don't know why.

basic_string&
operator+=(_CharT __c)
{
    this->push_back(__c);
    return *this;
}
like image 905
prehistoricpenguin Avatar asked Jul 22 '13 09:07

prehistoricpenguin


1 Answers

By adding 'a' + 'b' you will have 2 chars added together to form another char. Then you add it to the string with +=.

This code will do what you want:

std::string str;
( str += 'a' ) += 'b';

std::cout << str;
like image 172
Sergey K. Avatar answered Sep 20 '22 23:09

Sergey K.