【发布时间】:2012-01-30 09:41:31
【问题描述】:
过去一个小时我一直在寻找这个问题的答案,但找不到有效的解决方案。我正在尝试使用函数指针来调用特定对象的非静态成员函数。我的代码编译得很好,但是在运行时我得到一个讨厌的运行时异常,上面写着:
运行时检查失败 #0 - ESP 的值未在函数调用中正确保存。这通常是用一个调用约定声明的函数和一个用不同调用约定声明的函数指针调用的结果。
很多网站都说在方法头中指定调用约定,所以我在它前面加了__cdecl。但是,我的代码在更改后遇到了相同的运行时异常(我也尝试使用其他调用约定)。我不确定为什么我必须首先指定 cdecl,因为我的项目设置设置为 cdecl。我正在使用一些外部库,但在我添加这个函数指针之前,它们运行良好。
我正在关注这个:https://stackoverflow.com/a/151449
我的代码:
啊.h
#pragma once
class B;
typedef void (B::*ReceiverFunction)();
class A
{
public:
A();
~A();
void addEventListener(ReceiverFunction receiverFunction);
};
A.cpp
#include "A.h"
A::A(){}
A::~A(){}
void A::addEventListener(ReceiverFunction receiverFunction)
{
//Do nothing
}
B.h
#pragma once
#include <iostream>
#include "A.h"
class B
{
public:
B();
~B();
void testFunction();
void setA(A* a);
void addEvent();
private:
A* a;
};
B.cpp
#include "B.h"
B::B(){}
B::~B(){}
void B::setA(A* a)
{
this->a = a;
}
void B::addEvent()
{
a->addEventListener(&B::testFunction); //This is the offending line for the runtime exception
}
void B::testFunction()
{
//Nothing here
}
main.cpp
#include "A.h"
#include "B.h"
int main()
{
A* a = new A();
B* b = new B();
b->setA(a);
b->addEvent();
}
我正在使用 Visual Studio 2010 运行,但我希望我的代码能在其他平台上运行,只需进行少量更改。
【问题讨论】:
-
当然需要您的代码。但请记住举一个最小的例子。
-
注意非静态方法调用中的隐藏参数(
this指针) -
编译器和平台,请。
-
谢谢大家 - 我已经更新了我的帖子。 @LeleDumbo:我应该如何将“this”与函数指针一起使用?
-
你调用
receiverFunction的代码。最好提供一个显示问题且完整的小型 sn-p,即可以复制粘贴进行测试。
标签: c++ visual-studio-2010 function-pointers member-function-pointers