[英]C++ void pointer to get struct
I'm trying to learn void pointer. 我正在尝试学习空指针。 I want to get the passed struct contents using a void pointer.
我想使用空指针获取传递的结构内容。
Here is my struct: 这是我的结构:
Main.cpp Main.cpp
struct mynode
{
int id;
int amt;
};
struct mynode* myNode;
int main()
{
myclass mc;
mc.initialize(myNode);
getch();
}
myclass.cpp myclass.cpp
void initialize(void* data)
{
//how to get passed struct here ?
}
well, you can cast the pointer back to the original structure: 好了,您可以将指针转换回原始结构:
auto myStruct = static_cast<mynode*>(data);
although, your code is terribly C-like in the use of void*
. 但是,在使用
void*
,您的代码非常类似于C。
In C++, you are encouraged to use static polymorphism in the form of templates: 在C ++中,建议您以模板形式使用静态多态性:
template<class Dependency>
void initialize(Dependency& data){/*...*/}
or dynamic polymorphism, in the form of inheritance and overriding: 或动态多态,以继承和覆盖的形式:
struct BaseNode{
virtual ~BaseNode() = default;
};
struct MyNode : public BaseNode{};
void initialize (BaseNode* node){/*..*/};
The use of void*
in order to achieve generic code in C++ usually comes when dealing with C API's, like POSIX or Win32, and in your code you should avoid them. 在处理C API(例如POSIX或Win32)时,通常会使用
void*
来在C ++中实现通用代码,并且在代码中应避免使用它们。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.