简体   繁体   中英

AnsiString and += operator

this very little code fragment is heavily confusing me, although I'm only trying to concatenate to strings.

void __fastcall TForm1::Button1Click(TObject *Sender)
{
    AnsiString HelloWorld = "Hello ";
    HelloWorld += "World";

    TStringList *sl1 = new TStringList();
    sl1->Add("Hello");
    sl1->Strings[0] += " World";

    TStringList *sl2 = new TStringList();
    sl2->Add("Hello");
    sl2->Strings[0] = sl2->Strings[0] + " World";

    Memo1->Lines->Add( HelloWorld );         // prints "Hello World"
    Memo1->Lines->Add( sl1->Strings[0] );    // prints "Hello"  =====> WHY?
    Memo1->Lines->Add( sl2->Strings[0] );    // prints "Hello World"
}

Is the operator += not working on TStringList items?

What would be the proper way to do so?

Because when you use Strings[0] you are actually accessing a Property, and not the actual string. As such, when you use

sl1->Strings[0] += " World";

what is really happening is that you are invoking the read method for the property Strings, which is then resulting a string. On that resulting string, you are concatenating something else.

This is not changing the property's inner string at all.

In this case, just for the sake of understanding how it works, you could think that reading

sl1->Strings[0]

is the same as calling a function that returns a string (and in fact, it is! Because when you read a property it is running it's read method).

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