翻译:连波
23/11/2002
URL: http://www.zdnet.com.cn/developer/tech/story/0,2000081602,39099061,00.htm
字符串类的打印格式函数
对字符串包装类使用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 | convert to char | convert to constchar | convert to | convert to const | convert to | construct from char | construct from |
|
|
| yes, cast1 | yes, cast | yes, cast1 | yes, cast | yes2 | yes | yes |
|
|
| no | no | no | cast to | cast to | yes | yes |
|
| MBCS | no | yes, | no | no | no | yes | no |
|
| Unicode | no | no | no | yes, | no | no | yes |
|
|
| no | no | no | yes, cast | yes, cast | yes | yes |
|
|
| no | no | no | yes4 | yes4 | yes | yes |
|
|
| no6 | in MBCS | no6 | in Unicode | no5 | yes | yes |
|
|
| no | no | no | yes4 | yes4 | in MBCS builds | in Unicode builds |
附注:
-
虽然 _bstr_t 可以转换为非常量指针,但对内部缓冲区的修改可能导致内存溢出,或在释放BSTR时导致内存泄露。
- bstr_t 的BSTR内含 wchar_t* 变量,所以可将const wchar_t* 转换到BSTR。但这个用法将来可能会改变,使用时要小心。
- 如果转换到BSTR失败,将抛出异常。
- 用ChangeType()处理VARIANT的bstrVal。在MFC,转换失败将抛出异常。
- 虽然没有BSTR的转换函数,但AllocSysString()可返回一个新的BSTR。
- 用GetBuffer()方法可临时得到一个非常量TCHAR指针。
本文详细介绍了C++中各种字符串类之间的转换方法,包括_bstr_t、_variant_t、string、wstring等,并提供了实例说明如何正确地进行转换,避免常见的错误。
2961

被折叠的 条评论
为什么被折叠?



