【发布时间】:2018-03-09 07:00:44
【问题描述】:
好的,尽管 Stack 对 void* 的细节感到困惑,像 The C Programming Language (K&R) 和 The C++ Programming Language (Stroustrup) 这样的书。我学到了什么? void* 是一个没有类型推断的通用指针。它需要转换为任何已定义的类型,并且打印 void* 只会产生地址。
我还知道什么? void* 不能被取消引用,并且到目前为止仍然是 C/C++ 中的一项,我从中发现了很多关于但很少理解的内容。
我知道它必须被强制转换为*(char*)void*,但是对于generic 指针对我来说没有意义的是,我必须以某种方式已经知道我需要什么类型才能获取一个值。我是一名 Java 程序员;我了解泛型类型,但这是我遇到的问题。
所以我写了一些代码
typedef struct node
{
void* data;
node* link;
}Node;
typedef struct list
{
Node* head;
}List;
Node* add_new(void* data, Node* link);
void show(Node* head);
Node* add_new(void* data, Node* link)
{
Node* newNode = new Node();
newNode->data = data;
newNode->link = link;
return newNode;
}
void show(Node* head)
{
while (head != nullptr)
{
std::cout << head->data;
head = head->link;
}
}
int main()
{
List list;
list.head = nullptr;
list.head = add_new("My Name", list.head);
list.head = add_new("Your Name", list.head);
list.head = add_new("Our Name", list.head);
show(list.head);
fgetc(stdin);
return 0;
}
我稍后会处理内存释放。假设我不了解void* 中存储的类型,我该如何获取值? This 表示我已经需要知道类型,this 没有透露任何关于 void* 的通用性质,而我遵循 here 的含义,尽管仍然不了解。
为什么我期望void* 配合,编译器会自动抛出隐藏在堆或堆栈的某个寄存器中的内部类型?
【问题讨论】:
-
我认为
void*的使用是:Window的CWnd类可以容纳一个void* data。它不知道这些数据是什么,也不在乎。它对这个data没有任何作用,它只是为我保留它。同时,我的代码可以将我的thingamabob存储到这个data中。我的代码假定data始终包含thingamabob,这很好,因为我的代码是访问此data成员的唯一代码。我的代码“知道”类型,但CWnd不知道。
标签: c++11 c99 void-pointers