xin*_*aiz 3 c++ member-function-pointers
我得到一个小的"问题"与类方法的指针数组.
简而言之:我的班级综合体有四个功能 - double funX(void):
double fun1(void) const {...}
double fun2(void) const {...}
...
Run Code Online (Sandbox Code Playgroud)
然后我有一些指向上述配方的成员函数的指针.
double (Complex::*arr_ptr_fun[4])(void) const;
Run Code Online (Sandbox Code Playgroud)
我在构造函数初始化列表中初始化此数组:
... : re(_re), im(_im), arr_ptr_fun{&fun1,&fun2,&fun3,&fun4} { /*EMPTY*/ }
Run Code Online (Sandbox Code Playgroud)
当我尝试通过这个数组调用这4个函数中的任何一个时,例如:
std::cout << this->*arr_ptr_fun[0]();
Run Code Online (Sandbox Code Playgroud)
我收到一个我不明白的错误:
error: must use '.*' or '->*' to call pointer-to-member function in '((const Complex*)this)->Complex::arr_ptr_fun[0] (...)', e.g. '(... ->* ((const Complex*)this)->Complex::arr_ptr_fun[0]) (...)'
double fun4(void) const {std::cout << this->*arr_ptr_fun[0](); return sqrt(fun3());}
Run Code Online (Sandbox Code Playgroud)
使用.*或->*通过哪个指针...?(chaos *宇宙指针?)
有任何想法吗?
小智 6
你需要在括号中包围成员函数指针,
std::cout << (this->*arr_ptr_fun[0])();
Run Code Online (Sandbox Code Playgroud)
@Aldehir 给出的答案是您特定问题的正确答案。但是,如果您使用的是 C++11(或更高版本),那么使用std::mem_fn包装对成员函数的调用可能会方便得多。使用std::mem_fn您可以消除与.*和相关的问题->*。这是一个例子:
#include <iostream>
#include <functional>
#include <array>
class Complex
{
public:
double fun1() const {return 1;}
double fun2() const {return 2;}
double fun3() const {return 3;}
double fun4() const {return 4;}
using MemFun = decltype(std::mem_fn(&Complex::fun1)) ;
static const std::array<MemFun, 4> arr_ptr_fun ;
} ;
const std::array<Complex::MemFun, 4> Complex::arr_ptr_fun {{
std::mem_fn(&Complex::fun1),
std::mem_fn(&Complex::fun2),
std::mem_fn(&Complex::fun3),
std::mem_fn(&Complex::fun4)
}} ;
int main()
{
//
// Call all the member functions using object my_foo.
//
Complex my_foo ;
for(auto func: Complex::arr_ptr_fun)
{
std::cout << func(my_foo) << std::endl;
}
//
// The same as above but using array indexing.
//
for(size_t i=0; i<Complex::arr_ptr_fun.size(); ++i)
{
std::cout << Complex::arr_ptr_fun[i](my_foo) << std::endl ;
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
237 次 |
| 最近记录: |