初始化作为结构成员的函数指针时出错

Error when initialize a function pointer that is a struct member

本文关键字:函数 指针 出错 成员 结构 初始化      更新时间:2023-10-16

给定以下具有文件名和函数指针的结构:

static struct thread {
const char *const filename;
ssize_t (*in)(struct thread *, void *, size_t);
}

以及功能

int MyClass::read_wrap(struct stThread *t, void *buf, size_t nbytes)
{
return read(t->fd, buf, nbytes);
}

我尝试将函数read_wrap分配给结构对象中的函数指针成员:

int main (void)
{
thread myThread;
myThread.in = read_wrap;
}

但我得到了错误:

error: cannot convert MyClass::read_wrap’ from type ‘int (MyClass::)(stThread*, void*, size_t) {aka int (MyClass::)(stThread*, void*, unsigned int)}’ to type ‘int (*)(MyClass*, void*, size_t) {aka int (*)(stThread*, void*, unsigned int)}’

我的意思是,结构需要一个函数指针,当我把函数的名称传给它时,我想这是以某种方式转换成fp的?!这段代码来自C,使用gcc可以很好地编译。谢谢你的帮助!

成员函数指针的类型与普通函数指针不同。从错误中可以看出,指向read_wrap的成员函数指针的类型实际上是:

int (MyClass::*)(stThread*, void*, size_t)

重要的部分是MyClass::,这使得它与正常的函数指针不兼容。必须在MyClass的某个实例上调用此成员函数指针。

但是,由于read_wrap函数似乎甚至不使用MyClass的任何非静态成员,因此没有理由将其作为非静态成员函数。要么让它成为一个自由函数,要么让它变成一个静态成员,你的错误就会消失。

您正在初始化一个具有非静态成员函数地址(type ‘int (MyClass::)(stThread*, void*, size_t) {aka int (MyClass::)(stThread*, void*, unsigned int)}’)的未绑定函数ordinary function指针(type ‘int (*)(MyClass*, void*, size_t) {aka int (*)(stThread*, void*, unsigned int)}’)。需要更改声明的类型以与初始化的值相匹配。

尝试更改

ssize_t (*in)(struct thread *, void *, size_t);

ssize_t (MyClass::*in)(struct thread *, void *, size_t);