我很难解释我正在尝试做什么,我会尝试:想象一个class A包含一些变量的基类,以及一组派生的类,A它们都实现了一些bool test()对继承的变量进行操作的方法A.
class A {
protected:
int somevar;
// ...
};
class B : public A {
public:
bool test() {
return (somevar == 42);
}
};
class C : public A {
public:
bool test() {
return (somevar > 23);
}
};
// ... more classes deriving from A
Run Code Online (Sandbox Code Playgroud)
现在我有一个实例,class A并设置了值somevar.
int main(int, char* []) {
A a;
a.somevar = 42;
Run Code Online (Sandbox Code Playgroud)
现在,我需要某种容器,允许我迭代i这个容器的元素,i::test()在...的上下文中调用a:
std::vector<...> vec;
// push B and C into vec, this is pseudo-code
vec.push_back(&B);
vec.push_back(&C);
bool ret = true;
for(i = vec.begin(); i != vec.end(); ++i) {
// call B::test(), C::test(), setting *this to a
ret &= ( a .* (&(*i)::test) )();
}
return ret;
}
Run Code Online (Sandbox Code Playgroud)
我怎样才能做到这一点?我试过两种方法:
bool test()使得它采用类型的参数const A&而不是从A继承,我不太喜欢这个解决方案,因为somevar必须是公共的.编辑:
解决方案(1)是:
typedef bool (A::*)() mptr;
std::vector<mptr> vec;
vec.push_back(static_cast<mptr>(&T::test));
std::vector<mptr>::iterator i;
for(i = vec.begin(); i != vec.end(); ++i) {
(a .* (*i))();
}
Run Code Online (Sandbox Code Playgroud)
我不确定静态演员是否安全.
最干净的解决方案是你建议的最后一个,test在(纯)虚拟函数中A:
virtual bool test(const A& value) = 0;
Run Code Online (Sandbox Code Playgroud)
如果你对somevar公开保持私密并且仅提供公共获取功能感到困扰:
int getvar() const {return somevar;}
Run Code Online (Sandbox Code Playgroud)