C++ 表达式必须具有 Class 类型 - String 到 const char*
C++ Expression Must Have Class Type - String to const char*
尝试将 string
转换为 const char*
得到 "expression must have class type"
在底线。在没有运气的情况下尝试了一些转换变体。有任何想法吗?
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();
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*?
您在这段代码中犯了一些大错误,其中最重要的是您对文本缓冲区的管理完全不当,并且使用了无效的类型转换。就此而言,您不使用存储在缓冲区中的值,因此根本不需要分配它们,您可以为这些参数(以及您不使用的其他参数)传递 NULL,所以 GetVolumeInformation()
忽略它们。
至于实际的编译器错误,@vsoftco 已经回答了那个。您缺少实际 调用 GetMachineID()
所需的参数,并且您对 return 值的处理不当。
改用更像这样的东西:
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();
尝试将 string
转换为 const char*
得到 "expression must have class type"
在底线。在没有运气的情况下尝试了一些转换变体。有任何想法吗?
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();
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*?
您在这段代码中犯了一些大错误,其中最重要的是您对文本缓冲区的管理完全不当,并且使用了无效的类型转换。就此而言,您不使用存储在缓冲区中的值,因此根本不需要分配它们,您可以为这些参数(以及您不使用的其他参数)传递 NULL,所以 GetVolumeInformation()
忽略它们。
至于实际的编译器错误,@vsoftco 已经回答了那个。您缺少实际 调用 GetMachineID()
所需的参数,并且您对 return 值的处理不当。
改用更像这样的东西:
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();