我有一个接收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“。我如何做到这一点。
发布于 2012-10-18 15:52:08
使用特定于微软的_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 []等)释放它,并创建一个新的char*数组,在其中复制连接字符串的内容。就像这样
void MyClass::MyFunction(BSTR text)
{
_bstr_t name = "Name: " + _bstr_t(text, true);
// in case it was previously allocated with 'new'
// should be initialized to 0 in the constructor
delete [] m_classMember;
m_classMember = new char[name.length() + 1];
strcpy_s(m_classMember, name.length(), (LPCSTR)name);
m_classMember[name.length()] = 0;
}应该能做好这项工作。
发布于 2012-10-18 16:41:27
首先,我建议您不要将原始char/wchar_t*指针用作字符串的数据成员;一般来说,这样更好(更容易、更易维护、异常安全等)。使用健壮的C++ 字符串类。
由于您正在编写Windows代码,因此您可能希望使用ATL::CString,它在Win32编程环境中进行了很好的集成(例如:它提供了几个便利,比如从资源加载字符串,它可以开箱即用TCHAR模型,等等)。
如果您希望使用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。)
https://stackoverflow.com/questions/12948010
复制相似问题