我有 main.cpp 檔案,我在其中定義了一個結構:
struct values {
string name1;
string name2;
int key ;
} a;
在頭檔案 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 */
在我的Encrypt.cpp中:
void Encrypt::print(void * args)
{
struct values *a = args;
string name= a.name1;
cout<<"I'm"<<name<<endl;
};
這是我嘗試在main.cpp中創建指標的方法
void (Encrypt::* pointer_to_print) (void * args) = &Encrypt::print;
我得到的錯誤:
“不能用'void *'型別的左值初始化'struct values *'型別的變數”在Encrypt.cpp中
該行:
struct values *a = args;
評論
我這樣做是因為我想將具有超過 2 個引數的函式傳遞給函式:
pthread_create()
所以我的函式 print 只是我簡化的示例。
uj5u.com熱心網友回復:
問題是它args是型別void*并且a是型別values*所以你得到提到的錯誤。
要解決此問題,如果您確定允許強制轉換,您可以使用static_castto cast argsto :values*
values *a = static_cast<values*>(args);
另外更改a.name1為a->name1.
演示
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/496217.html
上一篇:無法列印類中的物件
