我有一个正在接收BSTR的类函数。在我的课堂上,我有一个成员变量,即LPCSTR。现在我需要附加BSTR ins LPCSTR。我怎么能这样做 这是我的功能。
void MyClass::MyFunction(BSTR text)
{
LPCSTR name = "Name: ";
m_classMember = name + text; // m_classMember is LPCSTR.
}
在我的m_classMember中我希望在此函数值之后应为“Name:text_received_in_function”。我怎么能做到这一点。
答案 0 :(得分:2)
使用Microsoft特定的_bstr_t
类,它本身处理ANSI / Unicode。像
#include <comutils.h>
// ...
void MyClass::MyFunction(BSTR text)
{
_bstr_t name = "Name: " + _bstr_t(text, true);
m_classMember = (LPCSTR)name;
}
是你几乎想要的。但是,正如备注所指出的,您必须管理m_classMember
的生命周期和连接的字符串。在上面的示例中,代码可能会崩溃。
如果您拥有MyClass
对象,则只需添加另一个成员变量:
class MyClass {
private:
_bstr_t m_concatened;
//...
};
然后使用m_classMember
作为指向m_concatened
字符串内容的指针。
void MyClass::MyFunction(BSTR text)
{
m_concatened = "Name: " + _bstr_t(text, true);
m_classMember = (LPCSTR)m_concatened;
}
否则,在分配m_classMember
之前,您应该以分配它(free
,delete []
等)的方式释放它,并创建一个新{{1}您复制连接字符串内容的数组。像
char*
应该做的工作。
答案 1 :(得分:1)
首先,我建议你不使用原始char/wchar_t*
指针作为字符串的数据成员;通常,使用强大的C ++ 字符串类会更好(更容易,更易于维护,异常安全等)。
由于您正在编写Windows代码,因此您可能希望使用ATL::CString
,它很好地集成在Win32编程的上下文中(例如:它提供了一些便利,例如从资源加载字符串,它可以解决-the-box with TCHAR
model等。)
如果您想使用TCHAR
模型(并使您的代码在ANSI / MBCS和Unicode版本中都可编辑),您可能希望使用ATL string conversion helper class CW2T
进行转换从ANSI {MBCS版本中的BSTR
(Unicode wchar_t*
)到char*
,并在Unicode版本中将其保留为wchar_t*
。
#include <atlstr.h> // for CString
#include <atlconv.h> // for CW2T
void MyClass::MyFunction(BSTR text)
{
// Assume:
// CString m_classMember;
m_classMember = _T("Name: ");
// Concatenate the content of the BSTR.
// CW2T keeps the BSTR as Unicode in Unicode builds,
// and converts to char* in ANSI/MBCS builds.
m_classMember += CW2T(text);
}
相反,如果你只想用Unicode编译你的代码(这在今天的世界中是有意义的),你可以摆脱_T("...")
装饰和CW2T
,只需使用:
void MyClass::MyFunction(BSTR text)
{
// Assume:
// CString m_classMember;
m_classMember = L"Name: ";
// Concatenate the content of the BSTR.
m_classMember += text;
}
(或者像其他人建议的那样使用STL的std::wstring
。)