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

来源:互联网 发布:plc转单片机 编辑:程序博客网 时间:2024/05/16 00:33
C++字符串完全指南(2) - 总结
翻译:连波
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
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_t3

cast to
_bstr_t3

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

附注:

  1. 虽然 _bstr_t 可以转换为非常量指针,但对内部缓冲区的修改可能导致内存溢出,或在释放BSTR时导致内存泄露。
  2. bstr_t 的BSTR内含 wchar_t* 变量,所以可将const wchar_t* 转换到BSTR。但这个用法将来可能会改变,使用时要小心。
  3. 如果转换到BSTR失败,将抛出异常。
  4. 用ChangeType()处理VARIANT的bstrVal。在MFC,转换失败将抛出异常。
  5. 虽然没有BSTR的转换函数,但AllocSysString()可返回一个新的BSTR。
  6. 用GetBuffer()方法可临时得到一个非常量TCHAR指针。