简体   繁体   中英

C++ Static function variable

In one of my methods, a function with two parameters is passed, and saved as rightClick. However, because its in a static function, the compiler wants the function to be initialised before. How can i go about this?

Mouse.cpp

void Mouse::clicked(int button, int state, int x, int y)
{
    if(button == GLUT_LEFT_BUTTON) {
        if(state == GLUT_DOWN) {
            isDragging = true;
            CurrentX = x;
            CurrentY = y;
        }
        else
        {
            isDragging = false;
        }
    }
    else if (button == GLUT_RIGHT_BUTTON)
    {
        if (state == GLUT_DOWN)
        {
            isDragging = true;
            rightClick(x,y);
        }
    }

}

void Mouse::setRightClickFunction(void (*func)(int, int))
{
    rightClick = func;
}

The setRightClickFunction is called before click ever is. Except now i'm getting a different problem : "Mouse::rightClick", referenced from: Mouse::clicked(int, int, int, int) in Mouse.o

Based on your comments, you're getting a linker error about "undefined reference to Mouse::rightClick . This has nothing to do with function pointers. It's just that whenever you declare a static data member in a class, it's only a declaration. You have to define it somewhere (= in exactly one .cpp file).

Assuming your class Mouse looks something like this:

class Mouse
{
  //...
  static void (*rightClick)(int, int);
  //...
};

You should put this line somewhere into Mouse.cpp :

void (*Mouse::rightClick)(int, int) = 0;

That will serve as the definition of the static data member rightClick .

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