x::GetX
は、メンバへのポインタである
が、この考えてみましょう。これらは非常に複雑な獣で、非メンバー機能を指すようにすることはできません。あなたはほぼ確実にそれは間違ってやっている、それしばらく -
#include <iostream>
int RtX(int a) // Global non-member function
{
return a * 4;
}
class x
{
public:
int(x::*GetVal)(int);
// This is an instance member function which acts as a proxy and calls the
// the global function
int RtX(int a) { return ::RtX(a); }
};
int main()
{
x a;
a.GetVal =&x.RtX; // Assign the member variable. Could do this in the
// constructor. **NOTE** No casts!
std::cout << (a.*GetVal)(4) << std::endl;
}
あなたが関数ポインタとポインタ・ツー・メンバー関数を扱うときに自分がキャストに手を伸ばす見つけた場合は、停止を次のコードは動作しますコンパイルすると、正しく実行されない可能性が非常に高いです。
また、コメントに記載されているように、std::function
を使用してください。
#include <iostream>
#include <functional>
int RtX(int a)
{
return a * 4;
}
class x
{
public:
std::function<int(int)> GetVal;
// Initialize GetVal in the constructor.
x() : GetVal(RtX)
{}
// Alternatively, you can initialize the variable in with a default
// initialization. You can also declare the member const if you don't want to
// change it later.
const std::function<int(int)> gv = RtX;
/*
};
int main()
{
x a;
std::cout << a.GetVal(4) << std::endl;
}
使用[ 'のstd :: function'](のhttp:// en.cppreference.com/w/cpp/utility/functional/function)と['std :: bind'](http://en.cppreference.com/w/cpp/utility/functional/bind)を参照してください。 –
あなたのエラーに関しては、メンバ関数は非メンバ関数と同じではありません。メンバ関数は呼び出されるオブジェクトのインスタンスを必要とし、非メンバ関数は呼び出されません。そのオブジェクトインスタンスは、しばしば隠し引数としてメンバ関数に渡され、非メンバ関数はその隠された引数を持たないため、単に形や形式に互換性がありません。 –
をバインドする代わりに、メンバー関数を呼び出して 'std :: function'オブジェクトに格納するlambaを使用することもできます。 – Hayt