您的位置:首页 > 编程语言 > C语言/C++

C++字符串完全指南(2) - 总结

2011-12-29 09:34 218 查看
[b]C++字符串完全指南(2) - 总结

[/b]

字符串类的打印格式函数
对字符串包装类使用printf()或其它类似功能的函数时要特别小心。包括sprintf()函数及其变种,以及TRACE 和ATLTRACE 宏。它们的参数都不做类型检验,一定要给它们传递C语言字符串,而不是整个string对象。

例如,要向ATLTRACE()传递一个_bstr_t 里的字符串,必须显式用(LPCSTR)或 (LPCWSTR)进行强制类型转换

_bstr_t bs = L"Bob!";
ATLTRACE("The string is: %s in line %d\n", (LPCSTR) bs, nLine);

如果忘了用强制类型转换,直接把整个 _bstr_t 对象传递给ATLTRACE,跟踪消息将输出无意义的东西,因为_bstr_t 变量内的所有数据都进栈了。

所有类的总结
常用的字符串类之间的转换方法是将源字符串转换为C类型字符串指针,然后将该指针传递给目标类的构造函数。下面列出将字符串转换为C类型指针的方法,以及哪些类的构造函数接受C类型指针。

Class
string

type

convert to char
*
?

convert to constchar
*
?

convert to
wchar_t*
?

convert to const
wchar_t*
?

convert to
BSTR
?

construct from char
*
?

construct from
wchar_t*
?

_bstr_t


BSTR


yes, cast1

yes, cast

yes, cast1

yes, cast

yes2

yes

yes

_variant_t


BSTR


no

no

no

cast to

_bstr_t
3

cast to

_bstr_t
3

yes

yes

string


MBCS

no

yes,
c_str()


method

no

no

no

yes

no

wstring


Unicode

no

no

no

yes,
c_str()


method

no

no

yes

CComBSTR


BSTR


no

no

no

yes, cast

to
BSTR


yes, cast

yes

yes

CComVariant


BSTR


no

no

no

yes4

yes4

yes

yes

CString


TCHAR


no6

in MBCS

builds, cast

no6

in Unicode

builds, cast

no5

yes

yes

COleVariant


BSTR


no

no

no

yes4

yes4

in MBCS builds

in Unicode builds

附注[b]:[/b]

虽然 _bstr_t 可以转换为非常量指针,但对内部缓冲区的修改可能导致内存溢出,或在释放BSTR时导致内存泄露。

bstr_t 的BSTR内含wchar_t* 变量,所以可将constwchar_t* 转换到BSTR。但这个用法将来可能会改变,使用时要小心。
如果转换到BSTR失败,将抛出异常。
用ChangeType()处理VARIANT的bstrVal。在MFC,转换失败将抛出异常。
虽然没有BSTR的转换函数,但AllocSysString()可返回一个新的BSTR。
用GetBuffer()方法可临时得到一个非常量TCHAR指针。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: