c++ - 错误 : invalid conversion from method to void*

标签 c++

我正在尝试将一个方法转换为空指针,以便我可以将它用作回调方法。

void* pVoidedFunc = &testmethod;

但是我得到了错误:

error: invalid conversion from int (*)() to void*

方法是:

static int testmethod()
{
   return 0;
}

如何将方法转换为 void 指针?

最佳答案

该语言不允许将指向函数的指针自动转换为空指针。

这是 C++ 标准草案 (N3337) 关于指针转换的内容(强调我的):

4.10 Pointer conversions

2 An rvalue of type “pointer to cv T,” where T is an object type, can be converted to an rvalue of type “pointer to cv void.” The result of converting a “pointer to cv T” to a “pointer to cv void” points to the start of the storage location where the object of type T resides, as if the object is a most derived object (1.8) of type T (that is, not a base class subobject).

函数不是对象。这在:

1.8 The C+ + object model

1 The constructs in a C + + program create, destroy, refer to, access, and manipulate objects. An object is a region of storage. [Note: A function is not an object, regardless of whether or not it occupies storage in the way that objects do. ]

对象类型定义为:

3.9 Types

9 An object type is a (possibly cv-qualified) type that is not a function type, not a reference type, and not a void type.

关于c++ - 错误 : invalid conversion from method to void*,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25816008/

相关文章:

c++ - Windows 与 Linux GCC argv[0] 值

c++ - clGetDeviceIds 返回 -1

c++ - 如何解决std::allocator的不推荐使用?

c++ - Ubuntu Linux 上的 Makefile C++11 错误

c++ - Q_OBJECT 抛出 'undefined reference to vtable' 错误

c++ - 静态常量类成员

c++ - 在哪里声明枚举

c++ - 破坏二叉搜索树时发生读取访问冲突

c++ - 模板函数特化默认

c++ - 了解 C++ 代码 - "Get the number of digits in an int"