c++ - 成员函数指针和继承

标签 c++ inheritance pointer-to-member

我需要解决这样的问题。 有一个基类和两个继承类。基类包含需要函数指针作为参数的方法。但是这样的函数是在继承的类中定义的。

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/

相关文章:

c++ - 为什么指向非静态成员函数的指针不能用作标准库算法的一元谓词?

c++ - 使用 QGLShaderProgram 将自定义类型(结构)统一从 Qt 传递到 GLSL

c++ - 没有匹配的构造函数来初始化模板类的构造函数

java - 我应该使用父类(super class)的 setter 从子类初始化其实例变量吗?

java - ArrayList继承实现

c++ - 其他成员函数的通用 'member function' 包装器?

c++ - 将派生类中指向成员函数的指针转换为指向抽象成员函数的指针

c++ - GetAsyncKeyState(VK_RETURN)遭遇

c++ - 将 char 转换为 ascii 值

c# - ASP.NET Web API 2重写继承属性路由操作发现多个操作