编译程序时遇到C ++ Visual Studio编译器错误“ htonf”

时间:2018-12-22 08:54:16

标签: c++ visual-studio

在编译代码时,我遇到了一些与“ htonf” c ++函数错误有关的错误。帮助将不胜感激。

以下是错误:

错误C2556'long htonf(float)':重载函数仅与'unsigned int htonf(float)'返回类型不同

错误C2371'htonf':重新定义;不同的基本类型ecueHost

错误C2065'htonf':未声明的标识符

错误出现在下面的datapacket.cpp中

#include "str.h"
#include "DataPacket.h"
#include "exception.h"
#include "message.h"
#include "object.h"
#include "util.h"


#define MAX_DATA_LENGTH  4096

long htonf(float f)
{
    long x;
    x = *((long*)&f);
    x = htonl(x);
    return x;
}

float ntohf(long l)
{
    float f;
    l = ntohl(l);
    f = *((float*)&l);
    return f;
}

在“ datapacket.h”头文件中包含的“ winsock2.h”头文件中,“ htonf”的定义如下:

#ifndef htonf
__inline unsigned __int32 htonf ( float Value ) 
{ 
unsigned __int32 Tempval;
unsigned __int32 Retval;
Tempval = *(unsigned __int32*)(&Value);
Retval = _WS2_32_WINSOCK_SWAP_LONG 
(Tempval);
return Retval;
}
#endif /* htonf */

并且在“ datapacket.cpp”文件本身中,“ htonf”也在此处声明

// Store a float to the datapacket
TDataPacket& TDataPacket::operator<<(float f)
{
long x = htonf(f);
return SerializingIn(&x, LONG_SIZE);
}

1 个答案:

答案 0 :(得分:0)

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<input id="id_st" type="text" name="st" value="0">
<br>
<button id="change_btn" type="button" name="button">change value</button>
<br>
<p id="p">value</p>

此错误消息完全解释了它。

您有:

Error C2556 'long htonf(float)': overloaded function differs only by return type from 'unsigned int htonf(float)'

在winsock2.h中,和

__inline unsigned __int32 htonf ( float Value ) 
在datapacket.cpp中的

。最简单的解决方案是更改datapacket.cpp中long htonf(float f) 的定义以匹配winsock2.h中的定义,并根据需要调整实现以反映新的返回类型。

首先,htonf()是有符号的,而long是无符号的;其次,即使在MSVC下它们的大小相同,unsigned __int32__int32也不能互换数据类型。