2015-11-12 10 views
8

これらの2つの関数の違いは何ですか?(funfun2fun2は関数ポインタですが、何がfunとなるのでしょうか?関数名であるポインタも渡しているので同じですか?関数ポインタ - 2つのオプション

#include <iostream> 

void print() 
{ 
    std::cout << "print()" << std::endl; 
} 

void fun(void cast()) 
{ 
    cast(); 
} 

void fun2(void(*cast)()) 
{ 
    cast(); 
} 

int main(){ 
    fun(print); 
    fun2(print); 
} 
+1

関数のパラメータ宣言は、関数へのポインタ型に調整されています。どちらも同等です。 – 0x499602D2

答えて

5

また、関数名であるポインタで渡すことがあるためという同じですか?

はい。これはCから継承されています。これは単に便宜上のものです。 funとfun2の両方が "void()"型のポインタを受け取ります。

このような利便性は、括弧付きの関数を呼び出すとAMBIGUITYが存在しないために存在します。 は、括弧で囲まれた引数リストがある場合は、関数を呼び出す必要があります。

あなたがコンパイルエラーを無効にした場合、次のコードでも動作します:

fun4(int* hello) { 
    hello(); // treat hello as a function pointer because of the() 
} 

fun4(&print); 

http://c-faq.com/~scs/cclass/int/sx10a.html

Why is using the function name as a function pointer equivalent to applying the address-of operator to the function name?