C++表达式必须具有类类型 - 字符串到const char*

mic*_*ell 0 .net c++ string char

尝试转换stringconst char*在底线给出"表达式必须具有类类型".尝试转换没有运气的一些变化.有任何想法吗?

string GetMachineID()
    {
        // LPCTSTR szHD = "C:\\";  // ERROR
        string ss;
        ss = "Err_StringIsNull";
        UCHAR szFileSys[255],
            szVolNameBuff[255];
        DWORD dwSerial;
        DWORD dwMFL;
        DWORD dwSysFlags;
        int error = 0;

        bool success = GetVolumeInformation(LPCTSTR("C:\\"), (LPTSTR)szVolNameBuff,
            255, &dwSerial,
            &dwMFL, &dwSysFlags,
            (LPTSTR)szFileSys,
            255);
        if (!success)
        {
            ss = "Err_Not_Elevated";
        }
        stringstream errorStream;
        errorStream << dwSerial;
        return string(errorStream.str().c_str());
    }

    const char *cstr = GetMachineID.c_str();
Run Code Online (Sandbox Code Playgroud)

vso*_*tco 6

const char *cstr = GetMachineID.c_str();
Run Code Online (Sandbox Code Playgroud)

一定是

const char *cstr = GetMachineID().c_str();
Run Code Online (Sandbox Code Playgroud)

但无论如何,想想你的指针会发生什么.它会悬空,因为std::string返回的对象GetMachineId()在语句结束时被销毁.

您应该为指针分配内存并使用a strcpy,或者,最好只是char*在代码中删除并std::string在任何地方使用.

相关:如何将std :: string转换为const char*或char*?