初始化作为结构成员的函数指针时出错
Error when initialize a function pointer that is a struct member
给定以下具有文件名和函数指针的结构:
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);
相关文章:
- QMetaObject invokeMethod的基于函数指针的语法
- C++-试图将函数指针推回到另一个CPP文件中的矢量时出错
- c++r值引用应用于函数指针
- 模板函数指针和lambda
- 是否可以将llvm::FunctionType转换为C/C++原始函数指针
- 带有类的函数指针
- () 函子后面的括号,而不是函数指针?
- 全局作用域中函数指针的赋值
- 使用"Task"函数指针队列定义作业管理器
- 将成员函数指针作为参数传递给模板方法
- 如何创建对象函数指针C++映射?
- 匹配函数指针作为模板参数?
- 通过函数指针定义类范围之外的方法
- 存储在类中的函数指针
- C++从函数指针数组调用函数
- 将返回值存储在函数指针数组的指针中是如何工作的?
- 整数键映射到头文件中的成员函数指针
- 从类成员函数到类 C 函数指针的转换
- 如何将内联匿名函数分配给C++函数指针
- 将字符缓冲区强制转换为函数指针