【发布时间】:2014-02-04 12:48:36
【问题描述】:
我正在尝试在 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 对象)obj 和func 变量为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();
};
【问题讨论】:
-
如果您认为
SlotMachine::CallbackGen的实现有助于破译您的问题,那么您是对的。 -
已添加,抱歉,我知道这里有很多代码,试图使其尽可能简单而不掩盖很多细节。
-
与您的问题无关,但您不必检查引用的地址是否为 NULL。引用必须始终有效。
标签: c++ object callback member assignment-operator