2
votes
CString Str1 = "ABC";
CString Str2 = Str1 + "123"; // Understandable
CString Str3 = "123" + Str1; // How does it work? Is there data overriding?

Does the last operation use CString '+' operator overloading, although Str1 is on the right of the '+'? Thanks of answering.

2
What's the reason for accepting the proposed answer, that doesn't answer your question, nor link to the correct documentation? - IInspectable

2 Answers

3
votes

The MFC/ATL CStringT class template provides the following operator+ operators as free functions:

friend CStringT operator+(const CStringT& str1, const CStringT& str2);
friend CStringT operator+(const CStringT& str1, PCXSTR psz2);
friend CStringT operator+(PCXSTR psz1, const CStringT& str2,);
friend CStringT operator+(char ch1, const CStringT& str2,);
friend CStringT operator+(const CStringT& str1, char ch2);
friend CStringT operator+(const CStringT& str1, wchar_t ch2);
friend CStringT operator+(wchar_t ch1, const CStringT& str2);

The statement CString Str3 = "123" + Str1; cannot use a class member, as there is no class object on the left-hand side of the + expression, and no user-defined implicit conversion operator. It needs to invoke a free function, and uses the overload taking a PCXSTR argument.

Note, that this implies, that your project is set to use ANSI (MBCS) encoding. This is not generally desirable. Use Unicode instead, either by setting the appropriate preprocessor symbols (see Working with Strings for details), or by explicitly using the wide character versions (CStringW) and prepending string literals with an L (L"123").

2
votes
CString Str3 = "123" + Str1;

Here you can see the various overloads of operator+ that CString supports and one of them includes the above example.

Note: Concatenating two string literals like below is not supported for that would be equivalent to adding two pointers.

CString Str3 = "123" + "456"