我想在C++中实现一个类b其中可以通过封装该迭代器类型的成员集进行某种迭代。像:传递成员函数作为参数/ C++
b_object.for_each_x_do(function_f);
所以function_f会得到X成员的每个人,做任何事情。假设:
void function_f(x_member_type x){ cout << x << endl; }
好的。所以我想实现通过像代码:
class b{
int *x;
public:
void foreach_x_do(void (*f)(int)){
while(*x++) // or any kind of iteration through x
f(*x);
}
};
class a{
b b_inst;
public:
void f(int x) { }
a(){
b_inst.foreach_x_do(f); // by mistake it was b_inst.foreach_x_do(f)(), however this wasn't the point at all.
}
~a(){}
};
int main(){}
不过,我得到这个错误,编译时间:
fp.cpp: In constructor
‘a::a()’
:
fp.cpp:17: error: no matching function for call to‘b::foreach_x_do(<unresolved overloaded function type>)’
fp.cpp:6: note: candidates are:void b::foreach_x_do(void (*)(int))
任何人都可以帮得到它来编译?
首先,传递给'foreach_x_do'的'f'不是'void(*)(int)'它是'void(a :: *)(int)'。 – steveo225 2011-05-19 18:26:01
只是一个旁注,你应该用大写命名你的类。所以'B类'而不是'B类'。只是为了符合常见的消息。 – Falmarri 2011-05-19 18:29:54
[此常见问题](http://www.parashift.com/c++-faq-lite/pointers-to-members.html)将为您提供比您想要了解的有关传递成员函数更多的信息。 – jedwards 2011-05-19 18:37:45