C 表达式必须具有类型 - 字符串到const char*
C++ Expression Must Have Class Type - String to const char*
尝试将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();
const char *cstr = GetMachineID.c_str();
必须是
const char *cstr = GetMachineID().c_str();
但是,无论如何,考虑一下您的指针会发生什么。它将悬挂,因为GetMachineId()
返回的std::string
对象在声明结束时被销毁。
您应该为指针分配内存并使用strcpy
,或者最好是在代码中摆脱char*
并在各处使用std::string
。
相关:如何将std ::字符串转换为const char*或char*?
您在此代码中犯了一些大错误,其中最重要的是您完全不夸张文本缓冲区,并使用无效的类型播种。为此,您不使用存储在缓冲区中的值,因此您根本不需要分配它们,您可以通过这些参数(以及其他您不使用的参数)传递null,因此GetVolumeInformation()
忽略他们。
至于实际的编译器错误,@vsoftco已经回答了一个。您缺少所需的参数来实际 call 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();