2017-05-06 58 views
0

我已經編寫了一個數組函數來在外部繪製openGL代碼,而無需在每次創建新函數時在Windows主循環中添加該函數。在數組函數指針中調用void void

它工作正常,但是當我將它指向另一個類中的公共void函數時,它說'必須調用對非靜態成員函數的引用'。

代碼:

int main(int argc, const char * argv[]) 
{ 
    Window* win = new Window(800, 600, "3D Game Engine"); 
    Game game; 
    win->draw[0] = a; 
    win->draw[1] = game.render; 

    win->MainLoop(); 
    delete win; 
} 

繪圖功能:

typedef void (*function_ptr)(int); 

function_ptr *draw = (function_ptr*)malloc(sizeof(function_ptr)); 

有沒有方法可以打電話了嗎?

感謝

+0

看看['std :: function'](http://en.cppreference.com/w/cpp/utility/functional/function)。 – Angew

+0

請問您可以發佈「窗口」類的定義 - 特別是「繪製」數組的定義嗎? –

回答

2

你的問題是下列之一:

void (*function_ptr)(int); 

是指向與該類型int的一個參數的函數。

如果你有這樣一個類的方法:

class exampleClass 
{ 
public: 
    void example(int a); 
}; 

A C++編譯器將內部生成功能與隱this說法 - 就像這樣:

void [email protected](exampleClass *this, int a); 

(內部大多數C++編譯器在這些函數的名稱中使用非法字符,如@ - 但這裏沒有關係。)

因此,您通常不能將類方法分配給這種類型的函數指針。您可以將(exampleClass *,int)類型的函數分配給(int)類型的函數指針。

爲了避免這種情況,編譯器通常不允許將類方法存儲在函數指針中。

「在所有」意味着,編譯器也不會允許你使用正確的內部類型的函數指針:

void (*function_ptr_2)(exampleClass *, int); 
exampleClass y; 

/* Not supported by the compiler although it is 
* theoretically possible: */ 
function_ptr_2 x1 = exampleClass::example; 
function_ptr_2 x2 = y.example; 

不幸的是我的C++知識是不夠好,所以我不能告訴你,如果和Angew的解決方案(std::function)是如何工作的。

+0

有幫助的閱讀:https://isocpp.org/wiki/faq/pointers-to-members – user4581301