类型为“const [structname] *”的参数与类型为“const [structname] *”的参数不兼容

Argument of type “const [structname] *” is incompatible with parameter of type “const [structname] *”

本文关键字:参数 类型 structname const 不兼容      更新时间:2023-10-16

我正在尝试在C++的库函数中包含结构。

结构是这样的:

struct NET_IN_OPERATE_FACERECONGNITIONDB{
DWORD                             dwSize;
EM_OPERATE_FACERECONGNITIONDB_TYPE    emOperateType;
FACERECOGNITION_PERSON_INFO       stPersonInfo;
char                              *pBuffer;
int                               nBufferLen;
};                                                `

包含它的函数是这样的:

BOOL CLIENT_OperateFaceRecognitionDB(
 LLONG                             lLoginID,
 const NET_IN_OPERATE_FACERECONGNITIONDB      *pstInParam,
 NET_OUT_OPERATE_FACERECONGNITIONDB      *pstOutParam,
 int                                 nWaitTime = 1000,
 );

我通过编写以下行来定义指针的结构:

const struct NET_OUT_OPERATE_FACERECONGNITIONDB{
    DWORD                             dwSize = sizeof(NET_IN_OPERATE_FACERECONGNITIONDB);
    EM_OPERATE_FACERECONGNITIONDB_TYPE    emOperateType = NET_FACERECONGNITIONDB_ADD;
    FACERECOGNITION_PERSON_INFO       FACERECOGNITION_PERSON_INFO1;
    char                              *pBuffer = '';
    int                               nBufferLen = 10;
} *pstInParam;

但是当我使用这一行将该结构调用到函数中时:

CLIENT_OperateFaceRecognitionDB(m_LoginID, pstInParam, pstOutParam, 1000);

我收到一条错误消息,说

类型为"const NET_IN_OPERATE_FACERECONGNITIONDB *"的参数与类型为"const NET_IN_OPERATE_FACERECONGNITIONDB *"的参数不兼容

这是非常不寻常的,因为参数和参数的类型相同。我犯了什么错误?

这是非常不寻常的,因为参数和参数的类型相同。

它们不属于同一类型(错误消息告诉您,尽管这样做不是很有帮助(。

这里发生的事情是,你的pstInParam声明实际上是在定义一个匿名struct,然后引入一个变量,该变量是指向这个匿名struct的指针。

这在

简化的示例中更容易看到,这在最近的 GCC 版本上会产生更有用的错误:

struct some_struct {
  int member;
};
bool some_function(const some_struct*) {
 return false;   
}
int main()
{
  const struct some_struct {
    int member = 0;
  } *param;
  some_function(param);
}
prog.cc: In function 'int main()':
prog.cc:15:22: error: cannot convert 'const main()::some_struct*' to 'const some_struct*' for argument '1' to 'bool some_function(const some_struct*)'
   some_function(param)

您(可能,取决于CLIENT_OperateFaceRecognitionDB的所有权语义(想要做的是声明一个some_struct并将其地址传递给函数:

int main()
{
  const some_struct param{0};
  some_function(&param);
}

。或者将其分配给免费商店:

int main()
{
  const some_struct* param = new some_struct{0};
  some_function(param);
  delete param;
}

在后一种情况下,如果可能,请考虑使用智能指针。