我正在尝试将 void 指针转换为回调函数中的类数组,该回调函数仅支持将 void 指针作为将参数传递给回调的一种方式。
class person
{
std::string name, age;
};
void callback (void *val)
{
for (int i = 0; i < 9; i++)
{
std::cout << (person [])val[i].name;
}
}
int main()
{
person p[10];
callback((void*)p);
}
我的目标是能够将类 person
的数组传递给回调,然后回调打印出姓名和年龄等数据。但是,编译不喜欢我正在做的事情并提示 error: request for member 'name' in 'val', which is of non-class type 'void*'
我该怎么做做这个?
最佳答案
如果你想恢复大小,你需要使用一个在运行时跟踪大小的容器。我建议使用 std::vector 而不是原始数组。
std::vector<person> p(10);
static_cast<std::vector<Person>*>(val);
关于c++ - 如何将 void 指针转换为类数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11068660/