Kev*_*inD 2 c++ pointers function member
我想有一个成员函数的指针成员.然后我可以将此指针设置为指向其他成员函数之一,并使用它来调用我真正想要的函数.本质上我有不同的方法来实现一个函数,我想设置一个指针来调用适当的函数.该类也是模板类.
我找不到通过函数指针调用函数的方法.例如:
template <typename T> class C
{
public:
typedef void(C<T>::*Cfunc)(int);
Cfunc cf;
void p1(int i) {
}
C (int i)
{
cf = &C<T>::p1;
}
};
int main ()
{
C<int> Try1(1);
(Try1.*C<int>::cf)(10);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我收到错误:
tc.cpp: In function ‘int main()’:
tc.cpp:5:11: error: invalid use of non-static data member ‘C<int>::cf’
Cfunc cf;
^
tc.cpp:16:16: error: from this location
(Try1.*C<int>::cf)(10);
Run Code Online (Sandbox Code Playgroud)
指向成员函数的指针不是静态变量,因此您需要一个实例C来访问它
int main()
{
C<int> Try1(1);
(Try1.*Try1.cf)(10);
return 0;
}
Run Code Online (Sandbox Code Playgroud)