简体   繁体   English

C ++从空铸造

[英]C++ Casting from void

I have a function that takes a void. 我有一个虚函数。 I am passing in an object (call is MyClass). 我传入一个对象(称为MyClass)。 The function is used to call a method from MyClass and return its output. 该函数用于从MyClass调用方法并返回其输出。 So, I am casting the object as itself (it was passed in as void) 因此,我将对象本身转换为对象(将其作为无效对象传入)

MyClass* func = dynamic_cast<MyClass*>(func1)

But, when I try to call a method from MyClass (func) I get this error... 但是,当我尝试从MyClass(func)调用方法时,出现此错误...

cannot convert 'MyClass::method' from type 'int (MyClass::)()' to type 'int'

My guess is that I am using the wrong method to cast the object. 我的猜测是我使用了错误的方法来投射对象。 Is that what the error is telling me? 那是错误告诉我的吗?

Any documentation you can point me to would be greatly appreciated. 您可以向我指出的任何文档将不胜感激。

EDIT This is my actual function 编辑这是我的实际功能

int call_method(void *func1)
{
    UserStatistics* func = dynamic_cast<UserStatistics*>(func1)
    return func->numCurrUsers;
}

The only thing I know about the UserStatistics class is that it has some virtual methods (like numCurrUsers) that return int. 我对UserStatistics类唯一了解的是,它具有一些返回int的虚拟方法(如numCurrUsers)。 I don't actually have access to the class itself, just documentation about how to access it. 我实际上没有访问该类本身的权限,而只是有关如何访问它的文档。

But, when I try to call a method from MyClass (func) I get this error... 但是,当我尝试从MyClass(func)调用方法时,出现此错误...

 cannot convert 'MyClass::method' from type 'int (MyClass::)()' to type 'int' 

My guess is that I am using the wrong method to cast the object. 我的猜测是我使用了错误的方法来投射对象。 Is that what the error is telling me? 那是错误告诉我的吗?

No. The error message is telling you that you are trying to return a pointer-to-method where an int is expected. 否。错误消息告诉您,您正在尝试返回预期为int的方法的指针。 And that is because of this statement: 这是因为此语句:

[UserStatistics] has some virtual methods (like numCurrUsers) that return int . [UserStatistics]具有一些返回int的虚拟方法(例如numCurrUsers)

That mean you need to call the method and return the value it returns, not return the method itself. 这意味着您需要调用该方法并返回其返回的值,而不是返回方法本身。

That has nothing to do with the cast itself. 这与演员本身无关。 And yes, you are using the wrong cast. 是的,您使用的是错误的演员表。 You need to use static_cast instead of dynamic_cast . 您需要使用static_cast而不是dynamic_cast

Try this: 尝试这个:

int call_method(void *func1)
{
    UserStatistics* func = static_cast<UserStatistics*>(func1)
    return func->numCurrUsers();
}

You use dynamic_cast only when you have a polymorphic implementation of classes. 仅在具有类的多态实现时才使用dynamic_cast Normally, when a base class pointer holds the address of a derived class object, you can dynamic_cast the base pointer to get the address of derived class object. 通常,当基类指针保存派生类对象的地址时,您可以dynamic_cast基指针获取派生类对象的地址。

In your case, you need to use static_cast instead: 在您的情况下,您需要改用static_cast

 static_cast<MyClass*>(func1);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM