[英]Create a pointer that points to a member function that takes a struct as an argument
I have main.cpp file where I defined a struct:我有 main.cpp 文件,我在其中定义了一个结构:
struct values {
string name1;
string name2;
int key ;
} a;
A class named Encrypt defined in a header file Encrypt.h and a file Encrypt.cpp where I define my functions... Im trying to create a pointer that points to a function that has a struct type as parameter here's how I did it: in my header file Encrypt.h在头文件 Encrypt.h 和一个文件 Encrypt.cpp 中定义了一个名为Encrypt的类,我在其中定义了我的函数...我试图创建一个指针,该指针指向一个具有结构类型作为参数的函数,我是这样做的:在我的头文件Encrypt.h
#ifndef Encrypt_h
#define Encrypt_h
#include<iostream>
using namespace std;
class Encrypt {
public:
void print(void *);
};
#endif /* Encrypt_h */
in my Encrypt.cpp :在我的Encrypt.cpp中:
void Encrypt::print(void * args)
{
struct values *a = args;
string name= a.name1;
cout<<"I'm"<<name<<endl;
};
here's how I tried to create the pointer in main.cpp这是我尝试在main.cpp中创建指针的方法
void (Encrypt::* pointer_to_print) (void * args) = &Encrypt::print;
THE ERROR I GET :我得到的错误:
" Cannot initialize a variable of type 'struct values *' with an lvalue of type 'void *' " in Encrypt.cpp “不能用'void *'类型的左值初始化'struct values *'类型的变量”在Encrypt.cpp中
the line :该行:
struct values *a = args;
REMARQUE评论
Im doing this because I want to pass a function with more than 2 parameters to the function : pthread_create()
so my function print is just I simplified example.我这样做是因为我想将一个具有超过 2 个参数的函数传递给函数: pthread_create()
所以我的函数 print 只是我简化的示例。
The problem is that args
is of type void*
and a
is of type values*
so you get the mentioned error.问题是args
是void*
类型,而a
是values*
类型,所以你会得到上面提到的错误。
To solve this uou can use static_cast
to cast args
to values*
if you're sure that the cast is allowed:要解决此问题,如果您确定允许强制转换,您可以使用static_cast
将args
转换为values*
:
values *a = static_cast<values*>(args);
Additionally change a.name1
to a->name1
.另外将a.name1
更改为a->name1
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.