我正在尝试将一个方法转换为空指针,以便我可以将它用作回调方法。
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
,” whereT
is an object type, can be converted to an rvalue of type “pointer to cvvoid
.” The result of converting a “pointer to cvT
” to a “pointer to cvvoid
” points to the start of the storage location where the object of typeT
resides, as if the object is a most derived object (1.8) of typeT
(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/