search

Home  >  Q&A  >  body text

C++中string类size

str.size() 输出结果不一样

str += 'a' + 'a';//报错

阿神阿神2806 days ago555

reply all(4)I'll reply

  • 迷茫

    迷茫2017-04-17 13:52:54

    This is because: the former is done first'

    And the latter appends two characters.

    In fact, the output of the two should be:

    ABCDa5
    ABCDrrreeea6
    

    Because

    The reason for the new error you posted is that 'a' = 97

    97 + 97 = 194

    exceeds the range of 0-127 ascii characters, so it is implicitly converted from a numerical value to a character report warning

    reply
    0
  • 大家讲道理

    大家讲道理2017-04-17 13:52:54

    This is a char type, not a constant string. First, according to the priority, the following '0'+'a' will be calculated first. For the char type, the addition is still a char type ('a'), so += Char type, only one character is actually appended.

        ¦ /**
        ¦  *  @brief  Append a character.
        ¦  *  @param c  The character to append.
        ¦  *  @return  Reference to this string.
        ¦  */
        ¦ basic_string&
        ¦ operator+=(_CharT __c)
        ¦ {
        this->push_back(__c);
        return *this;
        ¦ }

    reply
    0
  • ringa_lee

    ringa_lee2017-04-17 13:52:54

    Please do not send screenshots when sending codes.

    This is because (1) the operator precedence is different, + is higher than +=; (2) the operands of addition are different.

    s += '
    s += ('
    s = s + ('
    char tmp = '
    s += '
    std::string tmp = s + 'rrreee';
    s = tmp + 'a';
    '; s += 'a';
    ' + 'a'; s += tmp;
    ' + 'a');
    ' + 'a');
    ' + 'a';

    is equivalent to

    rrreee

    Similar to

    rrreee

    is equivalent to

    rrreee

    Adding two variables (characters) of type char is equivalent to adding the values ​​corresponding to the two characters, so ''+'a' is equivalent to 0 + 97, and the result is 97, which is the character 'a'.

    and

    rrreee

    Similar to

    rrreee The addition of

    std::string and char is equivalent to appending characters to the end of the string, so s + '' means adding a '' character to the end of the string.

    As for the warning of str += 'a' + 'a';//报错, it is the reason explained by @broken mirror, that is, character overflow.

    reply
    0
  • 黄舟

    黄舟2017-04-17 13:52:54

    '0' + 'a' gets a new character, so this is equivalent to:

    char c = 'rrreee' + 'a';
    s += c; // 只是添加了一个字符

    reply
    0
  • Cancelreply