当前位置导航:炫浪网>>网络学院>>编程开发>>C++教程>>C++进阶与实例

char* 转化为 CString的方法

 现在你有一个 char* 类型的数据,或者说一个字符串。怎么样创建 CString 对象呢?这里有一些例子:
char * p = \"This is a test\";

或者象下面这样更具有 Unicode 意识:

TCHAR * p = _T(\"This is a test\")

LPTSTR p = _T(\"This is a test\");

你可以使用下面任意一种写法:

CString s = \"This is a test\"; // 8-bit only
CString s = _T(\"This is a test\"); // Unicode-aware
CString s(\"This is a test\"); // 8-bit only
CString s(_T(\"This is a test\")); // Unicode-aware
CString s = p;
CString s(p);

  用这些方法可以轻松将常量字符串或指针转换成 CString。需要注意的是,字符的赋值总是被拷贝到 CString 对象中去的,所以你可以象下面这样操作,

TCHAR * p = _T(\"Gray\");
CString s(p);
p = _T(\"Cat\");
s += p;

结果字符串肯定是“GrayCat”。

CString 类还有几个其它的构造函数,但是这里我们不考虑它,如果你有兴趣可以自己查看相关文档。

事实上,CString 类的构造函数比我展示的要复杂,比如:

CString s = \"This is a test\"; 

  这是很草率的编码,但是实际上它在 Unicode 环境下能编译通过。它在运行时调用构造函数的 MultiByteToWideChar 操作将 8 位字符串转换成 16 位字符串。不管怎样,如果 char * 指针是网络上传输的 8 位数据,这种转换是很有用的。

相关内容
赞助商链接