我需要解决这样的问题。 有一个基类和两个继承类。基类包含需要函数指针作为参数的方法。但是这样的函数是在继承的类中定义的。
class CBase;
typedef bool (CBase::*FPredicate)();
class CBase
{
public:
CBase() {}
~CBase() {}
protected:
//this method waits until 'predicate' is true or until 'timeout' ms. passed
//and returns true if 'predicate' is true eventually
bool WaitEvent(FPredicate predicate, int timeout)
{
bool result = false;
int time1 = GetTickCount();
int time2;
bool isEnd = false;
while(!isEnd)
{
result = isEnd = (this->*predicate)();
time2 = GetTickCount();
if(time2 - time1 > timeout && !isEnd)
isEnd = true;
}
return result;
}
};
class CChildA : public CBase
{
protected:
bool a1() {/*some work*/}
bool a2() {/*some work*/}
void a_main()
{
...
WaitEvent(&CChildA::a1, 100);
...
WaitEvent(&CChildA::a2, 100);
...
}
};
class CChildB : public CBase
{
protected:
bool b1() {/*some work*/}
bool b2() {/*some work*/}
void b_main()
{
...
WaitEvent(&CChildB::b1, 100);
...
WaitEvent(&CChildB::b2, 100);
...
}
};
MSVC 2005 编译器在调用 WaitEvent 时出错:
error C2664: 'CBase::WaitEvent' : cannot convert parameter 1 from 'bool (__thiscall CChildA::* )(void)' to 'FPredicate'
一个问题是:我应该如何更改代码才能使其工作?将 WaitEvent 调用重写为是否安全
WaitEvent((FPredicate)(&CChildA::a1), 100)
?
在这种情况下,编译器没有报错,但它安全吗?或者有更好的解决问题的方法吗?
提前谢谢你。
最佳答案
问题是隐式传递的 this 类型不同。要么你投它,但在多重继承的情况下,这可能会失败。更好更强大的解决方案是将签名更改为:
template< typename T >
bool WaitEvent( bool ( T::*predicate )(), int timeout ) { ... }
关于c++ - 成员函数指针和继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9922392/