[英]How Can I Assign a Function to a Function Pointer
我希望能夠做這樣的事情:
void test();
void (*testPointer)() = SomethingThatReturnsAFunctionPointer();
test = testPointer;
我想做一些功能類似於實現openGL標頭的方法,在該方法中聲明函數原型,然后將函數設置為指針。 換句話說,我想知道一些openGL頭文件如何既可以加載openGL函數,又可以同時具有這些函數的原型。
函數不是變量; 他們不能被分配給。
但是,可以將函數隱式轉換為指向這些函數的指針。 函數本身仍然不是變量,但是您可以將該函數指針分配給為該函數指針適當鍵入的變量。
我想知道一些openGL頭文件如何既可以加載openGL函數,又可以同時具有這些函數的原型。
我不知道您要說的是哪個特定的標頭,但是我創建的加載器只是實現了函數調用函數指針的實現,將所有參數傳遞給它並返回其值(如果有)。 指針是在源文件中定義的,因此它不在標題本身中。
使用您的示例:
//header
void test();
//source file
void (*testPointer)();
void test()
{
testPointer();
}
您甚至可以幻想並test
加載指針 :
//source file
void (*testPointer)() == NULL;
void test()
{
if(!testPointer)
{
testPointer = SomethingThatReturnsAFunctionPointer();
}
testPointer();
}
第一:
int aplusb(int a, int b){return a + b;}
int aminusb(int a, int b){return a - b;}
int (*func)(int a, int b) = aplusb;
int some_func_caller ( int A, int B, int (*func)(int a, int b)){
return func(A, B);
}
int main(){
int a_ =10, b_ = 7;
int res1 = func(a_, b_);
int res2 = somefunc_caller(a_, b_, aminusb);
return 0;
}
第二名:
(如果您使用的是c ++編譯器)
typedef int MyFuncionType(int a, int b);
typedef int (*MyFuncionType2)(int a, int b);
int aplusb(int a, int b){return a + b;}
int aminusb(int a, int b){return a - b;}
int some_function_caller1(int a, int b, MyfunctionType fc){return fc(a,b);}
int some_function_caller2(int a, int b, MyfunctionType2 fc){return fc(a,b);}
int main(){
int a_ = 10, b_ = 7;
MyFunctionType *func1 = aminusb, *func2 = nullptr;
MyFunctionType2 func3 = aplusb, func4 = nullptr;
int res1 = func1(a_, b_);
int res2 = func3(a_, b_);
int res3 = some_function_caller1(a_, b_, aplusb);
int res4 = some_function_caller2(a_, b_, aminusb);
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.