I have a function that takes a void. I am passing in an object (call is MyClass). The function is used to call a method from MyClass and return its output. 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...
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. 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...
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. And that is because of this statement:
[UserStatistics] has some virtual methods (like numCurrUsers) that return int .
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
.
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. 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.
In your case, you need to use static_cast
instead:
static_cast<MyClass*>(func1);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.