gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 07:10:06 24 4
gpt4 key购买 nike

我正在尝试在 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) 是我遇到问题的地方。

赋值运算符函数中的回调对象(右轴对象)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();
};

最佳答案

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

关于c++ - 尝试在 C++ 中实现对方法的回调时的奇怪问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21147786/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com