[英]How to access an attribute into a struct from a void pointer?
我得到的任务是我看不到函数的详细功能,但我只知道id的功能。
所以我有一个函数,我们称它为“ get_button”,在文档中我知道“它返回指向按钮结构的指针”。 我知道按钮的结构,就像这样:
struct button{
int size;
char title;
short keyID;
};
该功能类似于:
void * get_button(int ID, int group)
但是我不知道它做什么。
现在我想知道标题,但是和编译器一起玩时,我得到了一个空指针作为回报。 那么我应该如何使用这个空指针? ASAIK我必须使用static_cast对其进行引用,但是在这种情况下是结构; 此外,我无法真正理解强制转换的含义以及如何使编译器知道我需要特定的结构。
这是一个特殊的情况,我需要知道如何将参数从void指针获取到结构中。 我不知道我是否应该使用static_cast或其他任何东西(因此我无法理解对其的引用)。 在这种情况下,我也不需要知道如何使用空指针! 我只需要知道如何访问结构中的属性即可。 我在这里和那里都看到了其他答案,但在这种情况下我找不到有价值的东西。
我真的不明白什么是铸造
您在下一个问题中回答自己:
如何使编译器知道我想要特定的结构。
就是这样 强制转换意味着您告诉编译器该对象具有特定类型。
这是一个特殊的情况,我需要知道如何将参数从void指针获取到结构中。
首先,将void指针转换为它指向的对象的指针类型: *button
。 然后,您可以使用正确类型的指针上的operator->
正常访问属性。
我不知道我应该使用static_cast还是其他方法
当将void指针转换为其他指针类型时,实际上应该使用static_cast
。
void* void_pointer = get_button(ID, group); // get the pointer
button* button_pointer = static_cast<button*>(void_pointer); // cast to the type of the pointed object
int size = button_pointer->size; // access the attribute through the pointer
这是一个简单的C旧样式的示例,该结构将结构转换为void指针:
#include <iostream>
using namespace std;
struct button{
int size;
char title;
short keyID;
};
int main()
{
button b;
b.size = 1;
b.title = 'c';
b.keyID = 2;
void *p = &b;
button *a = (button *)p;
std::cout << a->size << std::endl;
std::cout << a->title << std::endl;
std::cout << a->keyID << std::endl;
return 0;
}
指针基本上是内存中某个位置(在您的情况下为按钮结构)的地址。 当指针的类型更改为void *时,该地址不会更改,因此,如果提供get_button函数的库保证返回的指针实际上指向有效的按钮结构,则可以安全地将其强制转换回按钮*以便使用它(可以认为它为编译器提供了一些额外的信息)。
您将按以下步骤进行操作:
void *what_is_returned = get_button();
button *the_button = static_cast<button *>(what_is_returned);
char the_character_you_want = the_button->title;
->运算符的意思是“取消引用和访问成员”,它是取消引用左侧变量所包含内容(查找地址,如* the_button中的内容)然后访问该成员(如(* the_button).title中的内容的缩写)的简写形式。 ,有效地将title成员在按钮结构内的偏移量添加到按钮的地址,并从那里获取字符。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.