後でコンパイル エラーを解決しようとする場合でも、コンパイラの診断を読む必要があります。「いいえ」と言ったことは本当にありません。
Atypedef
は、関数ポインターを返す関数 (または関数ポインター) を宣言する場合に特に便利です。単純な関数ポインター型の式では、次のように書くときに括弧を覚えるだけでよいので、あまり役に立ちません。
int *ShowPopupMessage(const char*, char); // a function declaration
int (*ShowPopupMessage)(const char*, char); // a function pointer definition
どちらも C++ プログラマにとって読みやすいものです。
あなたの場合、(型を 2 回使用する必要があるため) aが望ましいかもしれませんが、受け入れ可能な暗黙的な変換を理解するのに問題があるように見えるので、カーテンtypedef
の後ろに問題を隠すつもりはありません。typedef
上記の例では、ほとんどの場合、左側のみを変更しています。C++ では、整数型から (任意の) ポインター型への暗黙的な変換が許可されていません。同様に、オブジェクト ポインター型から関数ポインター型への暗黙的な変換も許可されていません。整数を関数ポインターとして解釈する場合は、キャストが必要です。キャストだけでなくreinterpret_cast
、関数ポインター型へのキャストも必要です。
// this is OK (with the cast), but ShowPopupMessage is not a function pointer,
// but a pointer to int
int *ShowPopupMessage = (int*)0xDEADBEEF;
// this is incorrect, as C++ does not allow implicit conversions from
// object pointers to function pointers
int (*ShowPopupMessage)(const char*, char) = (int*)0xDEADBEEF;
// this is OK (assuming you know what you're doing with 0xDEADBEEF)
int (*ShowPopupMessage)(const char*, char) =
(int(*)(const char*, char))0xDEADBEEF;
// this is preferable in C++ (but it's not valid C)
int (*ShowPopupMessage)(const char*, char) =
reinterpret_cast<int(*)(const char*, char)>(0xDEADBEEF);
// (this is a possibility in C++11)
#include <functional>
std::function<int(const char*, char)> ShowPopupMessage =
reinterpret_cast<int(*)(const char*, char)>(0xDEADBEEF);
// it's used in much the same way as function pointers are
// i.e. you call it like you always call them: ShowPopupMessage("", ' ')