2012-08-09 65 views
0

我碰到下面的函數聲明,我不能夠理解它究竟是如何工作的: 功能在文件中聲明如下:理解的typedef

struct newtype { 
    /* some definition */ 
}; 

typedef void function1 (int* a, newtype* p); 

然後在其他C以上聲明代碼用於聲明另一個函數2如下:

function1 function2; 

void function2(int* a, newtype* p) 
{ 
    /* function definition */ 
} 

然後函數2的使用如下:

int function3 (int, char, function1*); 

/* definition */ 
function3(int a, char c, function2) 
{ 
    /* function definition */ 
} 

我無法理解聲明: function1 function2; 和typedef void function1(arguments)意味着什麼,因爲function1沒有聲明爲指針。任何人都可以解釋這裏發生了什麼?

+0

我無法獲得此代碼來編譯... – 2012-08-09 17:21:20

+0

[此typedef是什麼意思?函數原型?](http://stackoverflow.com/questions/3674200/what-does-this-typedef-mean-a-function-prototype) – jamesdlin 2012-08-09 19:13:26

回答

1

function1被聲明爲函數的類型,它不返回任何東西,並將指針指向一個int和一個指向newtype的指針作爲參數。

這種方式對於確保獲得符合特定格式的函數很有用,特別是在使用回調函數/函數指針時。

0
typedef void function1 (int* a, newtype* p); 

定義名稱功能1作爲void()(int *, newtype *)類型即函數的別名。

因此function1 function2;是與此相同的原型:

void function2 (int* a, newtype* p); 

名稱function1也可以用來聲明指針,這導致在一個熟悉的「函數指針」。這就是函數3在聲明int function3 (int, char, function1*);時所做的 - 它的最後一個參數是指向具有簽名的函數的指針void()(int *, newtype *)