简体   繁体   中英

Non static class used in another class <unresolved overloaded function type>

I'm struggling with using a non static function from one class inside another class. I've been reading some examples, but having a hard time understanding the basics of it. My best try so far, was by using the example given from http://www.newty.de/fpt/callback.html#static

I have two classes: ledStrips and MPTimers. MPTimers is a class to use timers on an Atmega. What I want, is to be able to call an instance of MPTimers within ledStrips. In the class of MPTimers, I can attach a callback function, which will be run each time the timer interrupts.

Here's an example of my code, only showing what's relevant.

MPTimers _timerOne;

// Constructor
ledStrips::ledStrips()
{
_timerOne.initialize(1000); // Set up timer with 1000 ms delay
_timerOne.attachFunction(timeout); // Attach a function to the timer
_timerOne.stop(); // Stop timer
}

The timeout function, which is the parameter in .attachFunction, is a member of ledStrips.

This is the code in MPTimers class

// AttachFunction
void MPTimers::attachFunction(void (*isr)() )
{
isrCallBack = isr;
}

And the error is: error: no matching function for call to 'MPTimers::attachFunction(unresolved overloaded function type).

I know it's because my instance of MPTimers have no idea to know, which instance the callback function is referering to, because it's a non static member of the class.

I tried the solution as described in the link, but with no succes. Hope that some of you can help me to figure this out :).

If you want to use a functer on a non-static member function, the syntax would be

void MPTimers::attachFunction(void (MPTimers::*isr)() )
{
isrCallBack = isr;
}

and if you want to call it later the syntax would be

{
[....]
this->*isrCallback()
[....]
}

You can't call a non-static method of a class without an object instanced from that class. MPTimers::attachFunction expects a static method or function. If your timeout function is a normal C function then there should be no problem (so it's obviously not the case), if it is a static method of a class then you should use ClassName::timeout, if it's a non-static method of a class then you can't do what you want, you'll need to modify your attachFunction and your MPTimers class to accept functors or object/method pairs (or use a static timeout method).

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.

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