简体   繁体   English

用C ++中的void指针算术

[英]Arithmetic with void pointers in C++

I need to access an object in a buffer, pointed by a void pointer. 我需要访问一个缓冲区中的对象,由void指针指向。 The object is located at a certain offset but since arithmetic on a void pointer is prohibited how can I access the object? 该对象位于某个偏移量,但由于禁止对void指针进行算术运算,因此如何访问该对象?

You can cast the pointer to char* (+1 on such pointer is offset by one byte) or any other pointer type if that suits your needs better. 您可以将指针转换为char* (此指针上的+1偏移一个字节)或任何其他指针类型(如果更适合您的需要)。

However, this approach is grossly error prone! 但是,这种方法非常容易出错! You better check your design, something smells here! 你最好检查一下你的设计,闻起来有些味道! void* are in 99% of cases unnecessary in C++, designs that use them are usually more "C" than "C++". void* C ++中,99%的情况都是不必要的,使用它们的设计通常比“C ++”更“C”。 Remember, templates and inheritance should be the way to do these things. 请记住,模板和继承应该是执行这些操作的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM