C和C++中struct的区别

Dal*_*ale 15 c c++ windows winapi kmdf

我试图将C++结构转换为C但仍然获得"未声明的标识符"?C++是否有不同的语法来引用结构?

struct KEY_STATE 
{
    bool kSHIFT; //if the shift key is pressed 
    bool kCAPSLOCK; //if the caps lock key is pressed down
    bool kCTRL; //if the control key is pressed down
    bool kALT; //if the alt key is pressed down
};
Run Code Online (Sandbox Code Playgroud)

我在另一个结构中使用KEY_STATE类型的变量:

typedef struct _DEVICE_EXTENSION
{
    WDFDEVICE WdfDevice;
    KEY_STATE kState;
} DEVICE_EXTENSION, *PDEVICE_EXTENSION;
Run Code Online (Sandbox Code Playgroud)

导致 错误C2061:语法错误:标识符'KEY_STATE'

...在KEY_STATE kState线上; 我正在使用WDK编译器构建,如果这有任何区别.这当然是在头文件中.我正在将C++ WDM驱动程序移植到WDF和C.

这是C2061的MSDN文章.

初始化器可以用括号括起来.要避免此问题,请将声明符括在括号中或使其成为typedef.

当编译器将表达式检测为类模板参数时,也可能导致此错误; 使用typename告诉编译器它是一个类型.

将KEY_STATE更改为typedef结构仍会导致此错误,实际上会导致更多错误.没有免费的括号或太多括号中的东西,这是文章建议的另一件事.

Tim*_*mbo 30

在C中,类型的名称是struct KEY_STATE.

所以你必须将第二个结构声明为

typedef struct _DEVICE_EXTENSION
{
    WDFDEVICE WdfDevice;
    struct KEY_STATE kState;
} DEVICE_EXTENSION, *PDEVICE_EXTENSION;
Run Code Online (Sandbox Code Playgroud)

如果您不想一直写struct,可以使用KEY_STATE类似于的typedef声明DEVICE_EXTENSION:

typedef struct _KEY_STATE
{
    /* ... */
} KEY_STATE;
Run Code Online (Sandbox Code Playgroud)


Ski*_*izz 16

bool在C99之前,C中没有类型.

此外,KEY_STATE当你这样做时,没有任何类型struct KEY_STATE.

试试这个:

typedef struct _KEY_STATE 
{
    unsigned kSHIFT : 1; //if the shift key is pressed 
    unsigned kCAPSLOCK : 1; //if the caps lock key is pressed down
    unsigned kCTRL : 1; //if the control key is pressed down
    unsigned kALT : 1; //if the alt key is pressed down
} KEY_STATE;
Run Code Online (Sandbox Code Playgroud)


hrn*_*rnt 6

你需要参考KEY_STATE使用struct KEY_STATE.在C++中,您可以将其保留struct,但不能保留在C语言中.

另一个解决方案是做一个类型别名:

typedef struct KEY_STATE KEY_STATE

现在KEY_STATE意味着同样的事情struct KEY_STATE


Tob*_*rre 5

您可以/应该键入结构,这样每次声明该类型的变量时都不需要struct关键字.

typedef struct _KEY_STATE 
{
    bool kSHIFT; //if the shift key is pressed 
    bool kCAPSLOCK; //if the caps lock key is pressed down
    bool kCTRL; //if the control key is pressed down
    bool kALT; //if the alt key is pressed down
} KEY_STATE;
Run Code Online (Sandbox Code Playgroud)

现在你可以这样做:

KEY_STATE kState;
Run Code Online (Sandbox Code Playgroud)

或者(如你所拥有的例子):

struct KEY_STATE kState;
Run Code Online (Sandbox Code Playgroud)