【问题标题】:C++ Expression Must Have Class Type - String to const char*C++ 表达式必须具有类类型 - 字符串到 const char*
【发布时间】:2015-05-16 00:36:54
【问题描述】:

尝试将string 转换为const 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();

【问题讨论】:

  • 不要将明确的char 与TCHARs 混为一谈;要么满TCHAR要么去wchar_t。
  • (例如 LPCTSTR("C:\\") 在 Unicode 构建中调用未定义的行为)

标签: c++ .net string char


【解决方案1】:
const char *cstr = GetMachineID.c_str();

必须

const char *cstr = GetMachineID().c_str();

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

您应该为指针分配内存并使用strcpy,或者最好在您的代码中去掉char*并在任何地方使用std::string。

相关:How to convert a std::string to const char* or char*?

【讨论】:

    【解决方案2】:

    你在这段代码中犯了一些大错误,其中最重要的是你完全错误地管理了你的文本缓冲区,并且使用了无效的类型转换。就此而言,您不使用存储在缓冲区中的值,因此您根本不需要分配它们,您可以为这些参数(以及您不使用的其他参数)传递 NULL 所以@987654321 @ 忽略它们。

    至于实际的编译器错误,@vsoftco 已经回答了那个问题。您缺少实际调用 GetMachineID() 所需的参数,并且您对返回值的处理不当。

    改用类似的东西:

    string GetMachineID()
    {
        DWORD dwSerial;
        ostringstream oss;
    
        if (!GetVolumeInformation(TEXT("C:\\"), NULL, 0, &dwSerial, NULL, NULL, NULL, 0);
            oss << "Err_Not_Retrieved_" << GetLastError();
        else
            oss << dwSerial;
    
        return oss.str();
    }
    

    std::string machid = GetMachineID();
    const char *cstr = machid.c_str();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-09-26
      • 1970-01-01
      • 2021-11-22
      • 2013-12-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多