C++ 中带有 void 指针的算术
我需要访问缓冲区中由 void 指针指向的对象。该对象位于某个偏移量处,但由于禁止对 void 指针进行算术,我如何访问该对象?
I need to access an object in a buffer, pointed by a void pointer. The object is located at a certain offset but since arithmetic on a void pointer is prohibited how can I access the object?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以将指针转换为
char*
(此类指针上的 +1 偏移一个字节)或任何其他指针类型(如果更适合您的需要)。然而,这种方法非常容易出错!你最好检查一下你的设计,这里有股味道!
void*
在 99% 的情况下在 C++ 中都是不必要的,使用它们的设计通常更“C”而不是“C++”。请记住,模板和继承应该是完成这些事情的方法。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.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++". Remember, templates and inheritance should be the way to do these things.