2016-08-12 12 views
-4

std :: functionメソッドを使用してC++ 11スタイルの関数ポインタを見つけました。次のシナリオは関数ポインタの古いメソッドでうまく動作しますが、新しいthingieで失敗します。関数の返り値としてstd :: functionを使用する

#include <functional> 
using namespace std; 
function<int(int,int)> arithmeticFcn; 

int add(int x,int y) 
{ 
return x + y; 
} 

arithmeticFcn getOperation(char op) 
{ 
switch (op) { 
case '+': 
return add; 
break; 
default: 
return add; 
break; 
} 
} 

int main() 
{ 
int x = 10,y = 20; 
char op1; 
cin >> op1; 
arithmeticFcn Fcn = getOperation(op1); 
cout << Fcn(x,y) << endl; 
return 0; 
} 

何か問題がありますか?

+1

'arithmeticFcn'が型を指していません。 –

+0

'return;壊す; '? 'break 'には決して到達しません。 –

+3

_ "新しいシナリオではシナリオ[..]が失敗します。" _これは受け入れ可能な問題記述ではありません。 –

答えて

2

私は手足に出て行って、あなたが以前に書いたことを推測するつもりだ:

typedef int arithmeticFcn(int, int); 

をし、関数ポインタこれと呼ばれます。

これは関数ポインタではありません。決して関数ポインタではありませんでした。 arithmeticFcnタイプのを作成しました。これは、上記のように使用できました。

しかし、ここで:

function<int(int,int)> arithmeticFcn; 

あなたはタイプを作成していません。あなたはarithmeticFcnと呼ばれるファンクタを作成しています。

私はあなたが意味を想像

typedef function<int(int,int)> arithmeticFcn; 
関連する問題