尝试在C ++中实现回调方法时的奇怪问题

时间:2014-01-15 20:42:52

标签: c++ object callback member assignment-operator

我正在尝试在C ++中实现对方法的回调。

注意:这松散地遵循http://www.codeproject.com/Articles/6136/Type-safe-Callbacks-in-C

处的代码

我创建了一个Callback类和一个派生自Callback类的CallbackGen类。

这是我用...创建的课程。

class ClassWithFunction
{
public:
    void TryAndCallMe(uint32_t x)
    {
        std::cout << "I was called!";
    }
};

然后在main()..

ClassWithFunction classWithFunction;

SlotMachine::CallbackGen<ClassWithFunction, void, uint32_t>
callBackGen(&classWithFunction, &ClassWithFunction::TryAndCallMe);

std::cout << "callbackGen.obj = " << callBackGen.obj << "\r\n"; // PRINTS 0x12345
printf("callbackGen.func = %p\r\n", callBackGen.func);  // PRINTS 0x12345

SlotMachine::Callback<void, uint32_t> callBack;

// THIS LINE CALLS THE ASSIGNMENT OPERATOR          
callBack = callBackGen;

然而,当代码进入重载赋值运算符

时,某些事情变得很古怪
Callback& operator=(const Callback<returnType, fArg1Type> &callback)
{
    std::cout << "Equal operator called.\r\n";
// Check if the right-hand side Callback object has been initialised
if(&callback != NULL)
{
    std::cout << "callback was not NULL.\r\n";
    this->obj = callback.obj;
    this->func = callback.func;

    std::cout << "callback.obj = " << callback.obj << "\r\n"; // PRINTS 0
    printf("callback.func = %p\r\n", callback.func);   // PRINTS (nil)
    std::cout << "this->obj = " << this->obj << "\r\n";  // PRINTS 0
    printf("this->func = %p\r\n", this->func);    // PRINTS (nil)
}
else
    Callback();

 return *this;

}

那些// PRINTS 0// PRINTS (nil)是我遇到问题的地方。

赋值运算符函数中的回调对象(RHS对象)objfunc变量为NULL!即使在输入赋值函数之前检查了“相同”值,并返回了有效的内存地址(其中显示// PRINTS 0x12345)。

编辑:为了使事情更清楚,这是班级CallbackGen

    //! @brief      This can generate callbacks to member functions!
    //! @details    Note that this has one more type than the callback classes, that is, a type for the object that the callback function belongs to.
    template<class objType, class returnType, class fArg1>
    class CallbackGen : public Callback<returnType, fArg1>
    {
    public:

        // Create method pointer type (points to method of a particular class
        typedef returnType (objType::*funcT)(fArg1);

        //! @brief      To store the pointer to the member callback function
        funcT func;

        //! @brief      To store the object that the callback function belongs to
        objType* obj;

        //! @brief      Constructor
        CallbackGen(objType* obj, funcT func)
        {
            this->func = func;
            this->obj = obj;
        }
    protected:
        CallbackGen();
    };

1 个答案:

答案 0 :(得分:1)

我的猜测是,在没有看到Callback类的定义的情况下,它有自己的objfunc成员,因为您通过assignement运算符中的Callback &访问它们。这些将被CallbackGen中声明的隐藏。换句话说,您没有访问正确的字段。