我试图将一个类方法指向一个全局函数,我已经看到this
但如果没有实例我怎么做不到呢?
考虑一下:
class x
{
public:
int(x::*GetVal)(int);
};
int RtX(int a)
{
return a * 4;
}
// declaration
int(x::*GetVal)(int) = (int(x::*)(int))&::Rtx; // :: global? // error
int main()
{
x a;
cout << (a.*GetVal)(4) << endl;
}
这会返回错误:
[Error] invalid cast from type 'int ()(int)' to type 'int (x::)(int)'
最佳答案
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;
}
关于c++ - 类非静态方法指向全局函数的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40299888/