简体   繁体   中英

How to store a function in a member of class? (Using function as callback)

I want to store a function as a class member and call it inside the class? Pretty much like a callback function. My class draw a document but every document must drawn differently. So I want to assign a function (written outside of the class) into one of the members of the class and then call it when I want to draw the document.

This function mostly is responsible for transforming objects according to each specific document.

Here is my class:

class CDocument
{
public:
    CDocument();
    ~CDocument();

    void *TransFunc();
}

void Transform()
{

}

int main()
    CDocument* Doc = new CDocument();
    Doc->TransFunc = Transform();
}

I know that this is probably simple question, but I couldn't find the answer by googling or searching SO.

I think, this is what you might want. Please get back to me if you have questions.

class CDocument
{
public:
    CDocument():myTransFunc(NULL){}
    ~CDocument();

    typedef void (*TransFunc)();  // Defines a function pointer type pointing to a void function which doesn't take any parameter.

    TransFunc myTransFunc;  //  Actually defines a member variable of this type.

    void drawSomething()
    {
         if(myTransFunc)
            (*myTransFunc)();   // Uses the member variable to call a supplied function.
    }
};

void Transform()
{

}

int main()
{
    CDocument* Doc = new CDocument();
    Doc->myTransFunc = Transform;  // Assigns the member function pointer to an actual function.
}

You need to use a Pointer to member function .

typedef void (CDocument::*TransFuncPtr)();

And then you can use TransFuncPtr as an type .


With your edit It seems like you just need a Pointer to a Free function.
Here is a small working sample .

#include<iostream>
#include<string>

typedef void (*TransFuncPtr)();

class Myclass
{
     public:
     TransFuncPtr m_funcPtr;
};

void doSomething(){std::cout<<"Callback Called";}

int main()
{
    Myclass obj;
    obj.m_funcPtr = &doSomething;
    obj.m_funcPtr();
    return 0;
}

The C declaration syntax, inherited by C++, is tricky.

Your declaration

void *TransFunc();

is actually the same as

void* TransFunc();

which declares a function returning a pointer, and not a pointer to a function.

To have the * bind to the declared name, and not to the type, you have to use an extra set of parenthesis

void (*TransFunc)();

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