C++ 在LPCSTR中附加BSTR

C++ 在LPCSTR中附加BSTR,c++,string-concatenation,bstr,lpcstr,C++,String Concatenation,Bstr,Lpcstr,我有一个接收BSTR的类函数。在我的类中,我有一个成员变量LPCSTR。现在我需要在LPCSTR中附加BSTR。我怎么能做到。 这是我的功能 void MyClass::MyFunction(BSTR text) { LPCSTR name = "Name: "; m_classMember = name + text; // m_classMember is LPCSTR. } 在我的m_类成员中,我希望在这个函数之后的值应该是“Name:text_received_in_f

我有一个接收BSTR的类函数。在我的类中,我有一个成员变量LPCSTR。现在我需要在LPCSTR中附加BSTR。我怎么能做到。 这是我的功能

void MyClass::MyFunction(BSTR text)
{
    LPCSTR name = "Name: ";
    m_classMember = name + text; // m_classMember is LPCSTR.
}

在我的m_类成员中,我希望在这个函数之后的值应该是“Name:text_received_in_function”。如何做到这一点。

使用特定于Microsoft的类,该类以本机方式处理ANSI/Unicode。差不多

#include <comutils.h>
// ...

void MyClass::MyFunction(BSTR text)
{
    _bstr_t name = "Name: " + _bstr_t(text, true);
    m_classMember = (LPCSTR)name;
}
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;
}
然后使用
m_classMember
作为指向
m_concated
的字符串内容的指针

void MyClass::MyFunction(BSTR text)
{
    m_concatened = "Name: " + _bstr_t(text, true);
    m_classMember = (LPCSTR)m_concatened;
}
否则,在分配
m_classMember
之前,您应该以分配它的相同方式释放它(
free
delete[]
,等等),并创建一个新的
char*
数组,在其中复制特定字符串的内容。差不多

#include <comutils.h>
// ...

void MyClass::MyFunction(BSTR text)
{
    _bstr_t name = "Name: " + _bstr_t(text, true);
    m_classMember = (LPCSTR)name;
}
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;
}
应该做这项工作。

首先,我建议您不要使用原始
char/wchar\t*
指针作为字符串的数据成员;一般来说,使用健壮的C++ >强>字符串类

比较好(更容易、更容易维护、异常安全等)。 由于您正在编写Windows代码,您可能希望使用
ATL::CString
,它在Win32编程环境中得到了很好的集成(例如:它提供了一些便利,如从资源加载字符串,它与
TCHAR
模型一起开箱即用等)

如果您想使用
TCHAR
模型(并使您的代码在ANSI/MBCS和Unicode版本中都可编译),您可能需要使用
CW2T
BSTR
(即Unicode
wchar\u t*
)转换为ANSI/MBCS版本中的
char*
,并在Unicode版本中保持为
wchar\u*

#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);
}

(或者按照其他人的建议使用STL的
std::wstring

这是类的成员,它是LPCSTR,我应该在这里使用什么,它没有指向任何东西,