[英]error C2275 : illegal use of this type as an expression
從昨天開始,我一直在為C項目遇到編譯錯誤。 該項目本身包括創建將執行某些任務的服務。
自昨天以來,我沒有什么改變,但是今天早上,我的代碼無法編譯了。
這是我的錯誤:
c:\path\main.c(56): error C2275: 'SERVICE_TABLE_ENTRY' : illegal use of this type as an expression
c:\program files\microsoft sdks\windows\v7.0a\include\winsvc.h(773) : see declaration of 'SERVICE_TABLE_ENTRY'
c:\path\main.c(56): error C2146: syntax error : missing ';' before identifier 'DispatchTable'
c:\path\main.c(56): error C2065: 'DispatchTable' : undeclared identifier
c:\path\main.c(56): error C2059: syntax error : ']'
c:\path\main.c(57): error C2065: 'DispatchTable' : undeclared identifier
c:\path\main.c(57): warning C4047: 'function' : 'const SERVICE_TABLE_ENTRYA *' differs in levels of indirection from 'int'
c:\path\main.c(57): warning C4024: 'StartServiceCtrlDispatcherA' : different types for formal and actual parameter 1
這是與這些錯誤有關的代碼(從第45行到第58行):
int main(int ac, char *av[])
{
if (ac > 1)
{
if (!parse_args(ac, av))
{
aff_error(ARGUMENTS);
return EXIT_FAILURE;
}
}
SERVICE_TABLE_ENTRY DispatchTable[] = {{MY_SERVICE_NAME, ServiceMain}, {NULL, NULL}};
StartServiceCtrlDispatcher(DispatchTable);
return EXIT_SUCCESS;
}
這是我的ServiceMain函數的代碼:
void WINAPI ServiceMain(DWORD ac, LPTSTR *av)
{
gl_ServiceStatus.dwServiceType = SERVICE_WIN32;
gl_ServiceStatus.dwCurrentState = SERVICE_START_PENDING;
gl_ServiceStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP;
gl_ServiceStatus.dwWin32ExitCode = 0;
gl_ServiceStatus.dwServiceSpecificExitCode = 0;
gl_ServiceStatus.dwCheckPoint = 0;
gl_ServiceStatus.dwWaitHint = 0;
gl_ServiceStatusHandle = RegisterServiceCtrlHandler(MY_SERVICE_NAME, ServiceCtrlHandler);
if (gl_ServiceStatusHandle == (SERVICE_STATUS_HANDLE)0)
return;
gl_ServiceStatus.dwCurrentState = SERVICE_RUNNING;
gl_ServiceStatus.dwCheckPoint = 0;
gl_ServiceStatus.dwWaitHint = 0;
SetServiceStatus(gl_ServiceStatusHandle, &gl_ServiceStatus);
}
我無法找到適合我問題的答案,有人可以幫忙嗎? 謝謝 !
當您將源文件命名為*.c
,MSVC假定它正在編譯C,即C89。 所有塊局部變量都需要在塊的開始處聲明。
解決方法包括:
{
)聲明/初始化所有局部變量 *.cpp
或等效文件,然后編譯為C ++。 您可能使用的C版本不允許在塊的中間聲明變量。 C過去常要求變量在塊{的開頭,在{之后,在可執行語句之前)聲明。
在使用該變量的代碼周圍放括號。
在您的情況下,這意味着:
if (ac > 1)
{
if (!parse_args(ac, av))
{
aff_error(ARGUMENTS);
return EXIT_FAILURE;
}
}
{
SERVICE_TABLE_ENTRY DispatchTable[] = {{MY_SERVICE_NAME, ServiceMain}, {NULL, NULL}};
StartServiceCtrlDispatcher(DispatchTable);
}
將項目從一種安裝轉移到另一種安裝時發生此錯誤(VS2015 => VS2010)。
實際上,C代碼是在原始計算機上編譯為C ++的,而在目標計算機上,即使源文件的類型為* .cpp,它在Project Properties\\C/C++\\Advanced\\Compile as
的“默認”設置也以某種方式指向了C 。
在我的小程序中,關於某些類型的代碼(例如HWND
和HRESULT
)以及不同格式的for
循環以及C ++構造(例如LPCTSTR,
size_t
, StringCbPrintf
和BOOL
。 比較 。
將“編譯為”從Default
更改Compile as C++ Code (/TP)
解決。
這也將使您“非法使用此類型作為表達式”。
錯誤:
MyClass::MyClass()
{
*MyClass _self = this;
}
正確:
MyClass::MyClass()
{
MyClass* _self = this;
}
您可能想知道代碼的重點。 通過顯式轉換為我認為是的類型,當編譯器拋出錯誤時,我意識到當試圖將“ this”發送給另一個對象的構造函數時,我忽略了類名前面的一些匈牙利符號。 尋找錯誤時,最好測試一下所有假設。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.