是否允许将char []强制转换为unsigned char *?

时间:2013-12-24 10:13:03

标签: c++

我正在使用一些有一个方法要求的类:

const unsigned char *sData

作为参数。

当我打电话给跟随时:

char dataIn[]="The quick brown fox jumps over the lazy dog";     
obj.CRC(dataIn,strlen(dataIn),&checksum); // compute checksum

我收到了错误:

Error   1   error C2664: 'void crcClass::CRC(const unsigned char *,size_t,unsigned int *)' : cannot convert parameter 1 from 'char [44]' to 'const unsigned char *' 

所以我修改了上面这样的代码并且它可以工作:

obj.CRC((const unsigned char*)dataIn,strlen(dataIn),&checksum); // compute checksum

我做的修改是否正常?

2 个答案:

答案 0 :(得分:7)

没关系,但为了“安全”,请考虑改用reinterpret_cast<const unsigned char*>(dataIn)

reinterpret_cast无法移除constvolatile的意义上,这是更安全的,而C风格的演员可以。如果你不想删除限定符,那么当你弄错了代码就很难编译。

当然,在这种情况下,错误的可能性很小 - 目的地为const - 合格,您可能会注意到来源是volatile - 合格。但是养成让编译器帮助你的习惯仍然很有用,而且有些人会认为代码更容易阅读。

答案 1 :(得分:0)

如果可能的话,为普通char添加一个重载,并隐藏CRC类内的强制转换:

class crc32 {

    // ...
    unsigned int CRC(unsigned char const *in) { 
       // existing function
    }

    unsigned int CRC(char const *in) { 
       // pass through to preceding function:
       return CRC(reinterpret_cast<unsigned char const *>(in);
    }
};

我还注意到,乍一看crc32::CRC看起来对我很怀疑。看起来更有意义的是将其写成operator()的重载。

相关问题