C++ C++;空铸

C++ C++;空铸,c++,casting,C++,Casting,我有一个空的函数。我正在传入一个对象(调用是MyClass)。该函数用于从MyClass调用方法并返回其输出。因此,我将对象转换为自身(它作为void传入) 我的猜测是我使用了错误的方法来投射对象。这就是错误告诉我的吗 如果您能为我提供任何文件,我将不胜感激 编辑 这是我的实际功能 int call_method(void *func1) { UserStatistics* func = dynamic_cast<UserStatistics*>(func1) ret

我有一个空的函数。我正在传入一个对象(调用是MyClass)。该函数用于从MyClass调用方法并返回其输出。因此,我将对象转换为自身(它作为void传入)

我的猜测是我使用了错误的方法来投射对象。这就是错误告诉我的吗

如果您能为我提供任何文件,我将不胜感激

编辑 这是我的实际功能

int call_method(void *func1)
{
    UserStatistics* func = dynamic_cast<UserStatistics*>(func1)
    return func->numCurrUsers;
}
int调用方法(void*func1)
{
UserStatistics*func=dynamic\u cast(func1)
返回func->numCurrUsers;
}

关于UserStatistics类,我只知道它有一些返回int的虚拟方法(比如numCurrUsers)。我实际上没有访问该类本身的权限,只有关于如何访问该类的文档。

只有在类的多态实现时,才使用
dynamic\u cast
。通常,当基类指针持有派生类对象的地址时,您可以
dynamic\u cast
基类指针来获取派生类对象的地址

在您的情况下,您需要使用
static\u cast

 static_cast<MyClass*>(func1);
static_cast(func1);
但是,当我试图从MyClass(func)调用一个方法时,我得到了这个错误

cannot convert 'MyClass::method' from type 'int (MyClass::)()' to type 'int'
cannot convert 'MyClass::method' from type 'int (MyClass::)()' to type 'int'
我的猜测是我使用了错误的方法来投射对象。这就是错误告诉我的吗

否。错误消息告诉您正在尝试返回一个指向方法的指针,该方法需要
int
。这是因为这句话:

[UserStatistics]有一些返回int的虚拟方法(如numCurrUsers)

这意味着您需要调用方法并返回它返回的值,而不是返回方法本身

这与演员本身无关。是的,你用错了演员阵容。您需要使用
static\u cast
而不是
dynamic\u cast

试试这个:

int call_method(void *func1)
{
    UserStatistics* func = static_cast<UserStatistics*>(func1)
    return func->numCurrUsers();
}
int调用方法(void*func1)
{
UserStatistics*func=static\u cast(func1)
返回func->numCurrUsers();
}

你需要一个密码,你需要以
void*
的身份传入。我无法复制。我得到了一个不同的编译错误:@dgsomerton
static_cast
是合适的cast,而不是
reinterpret_cast
另外,您需要实际调用成员函数:
return func->numCurrUsers()括号不是可选的。
int call_method(void *func1)
{
    UserStatistics* func = static_cast<UserStatistics*>(func1)
    return func->numCurrUsers();
}