CString Str1 = "ABC";
CString Str2 = Str1 + "123"; // Understandable
CString Str3 = "123" + Str1; // How does it work? Is there data overriding?
最后一个操作是否使用了 CString '+' 运算符重载,尽管 Str1 位于 '+' 的右侧? 感谢您的回答。
最佳答案
MFC/ATL CStringT类模板提供以下operator+运算符作为自由函数:
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);
语句CString Str3 = "123"+ Str1;
不能使用类成员,因为+
表达式的左侧没有类对象,并且没有用户定义的隐式转换运算符。它需要调用一个自由函数,并使用带有 PCXSTR 的重载。论证。
请注意,这意味着您的项目设置为使用 ANSI (MBCS) 编码。这通常是不可取的。请改用 Unicode,方法是设置适当的预处理器符号(有关详细信息,请参阅 Working with Strings),或者显式使用宽字符版本 (CStringW
) 并在字符串文字前面添加 L
(L“123”
)。
关于c++ - MFC CString 构造函数操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53313783/