MFC中CString与string的区别以及相互转换关系

原贴地址:https://blog.csdn.net/ljsant/article/details/53167621

区别:

CString 类是微软的visual c++提供的MFC里面的一个类,所以只有支持MFC的工程才可以使用。如在linux上的工程就不能用CString了,只能用标准C++中的 string类了。另外,因为string类是在c++标准库中,所以它被封装在了std命名空间中,使用之前需要声明using namespace std;而CString类并不在std命名空间中,因为它不是c++的标准库,只是微软的一个封装库。这点看来用string类的程序的移植性更好。

(1)string 是 语言的东西 是c++语言的CString 是VC++ IDE内嵌的,是MFC的 。不是一个概念。
         CString 离开VC++不能用string 在任何支持C++的IDE中都能用
(2)string类既是一个标准c++的类库,同时也是STL(Standard Template Library,标准模版库)中的类库,所以支持Iterator操作。
(3)CString类和string类提供的方法接口并不完全相同,所以不要糊里糊涂的认为某个类中怎么没有另外一个类中的方法啊。:-)。。

(4)他们和char*之间的转换方法也不一样。


转换:

(1)如果在MFC的UNICODE环境下,两者转换比较麻烦:

//方法一
CString theCStr;
std::string STDStr( CW2A( theCStr.GetString() ) );
//方法二
CString m_Name;
CT2CA pszName(m_Name);
std::string m_NameStd(pszName);
//方法三
CString str = L"Test";
std::wstring ws(str);
std::string s; 
s.assign(ws.begin(), ws.end());

(2)如果在多字符集的环境下,就比较简单:

1.string -> CString   :CString.format("%s", string.c_str());    (用c_str()确实比data()要好. )

2,CString -> string :string s(CString.GetBuffer()); (GetBuffer()后一定要ReleaseBuffer(),否则就没有释放缓冲区所占的空间.

猜你喜欢

转载自blog.csdn.net/qq_37059136/article/details/80705767