c++ - VC++中通过A类函数指针调用B类成员函数

标签 c++ pointers visual-c++ function-pointers pointer-to-member

让我通过一个例子来解释我的问题(使用 VS2013 的 VC++ 代码)。

void Imhere(int num)
{
    printf_s("\n Hello World printed %d\n",num);
}
class Abc;
class Dllclas
{
    public:
    void dllFunc()
    {
        printf_s("\n Heelo this is DLl func\n");
    }
};

void outsideFunc()
{
    printf_s("\n Heelo this is outside func\n");
}
typedef void(*outsideFP)();
typedef void (Dllclas::*funcFP)();
class Abc
{
public:
    funcFP fp;
    outsideFP outFp;
    int a;
    void assignOUTFp()
    {
        outFp = &outsideFunc;
    }
    void assignFP()
    {
        fp = &(Dllclas::dllFunc);
    }
};

int _tmain(int argc, _TCHAR* argv[])
{

    Abc* abcObj1 = new Abc();
    abcObj1->a = 7;

    abcObj1->assignOUTFp(); 
    abcObj1->outFp();  // THIS FUNCTION CALL WORKS PERFECTLY FINE.

    abcObj1->assignFP();
    abcObj1->fp(); // COMPILATION ERROR. 

在此代码片段的最后一行

abcObj1->fp(); // COMPILATION ERROR.

我遇到编译错误。

error C2064: term does not evaluate to a function taking 0 arguments

此外,如果我将鼠标悬停在“abcObj1->fp()”上,我会收到一个红色错误,内容为“

expression preceding parentheses of apparent call must have (pointer-to-) function type

在这里,我可以调用任何类之外的函数“abcObj1->outFp();”。 因此,我知道收到此错误的原因是因为“abcObj1->fp();”中存在函数地址。属于类成员函数,即 Dllclas 类的“dllFunc()”。

我还引用了链接 link,但我无法解决编译错误。

我可以获得代码示例方面的帮助吗? 提前致谢。

最佳答案

第一个错误可以通过删除括号来修复:

fp = &Dllclas::dllFunc; // This will compile

第二个问题更难解决:回想一下,为了调用成员函数,您需要两件事:

  • 指向函数的指针,以及
  • 您调用函数的对象。

因此,您需要一个 Dllclas 类型的“目标”对象还有:

Dllclas target;
(target.*abcObj1->fp)();

这里的语法有点疯狂 - .*应用通过 abcObj1->fp 获得的函数指针到调用的目标,即 Dllclas 类型的对象。如果您有指向目标的指针而不是目标本身,请使用 ->*运算符:

Dllclas *targetPtr;
(targetPtr->*abcObj1->fp)();

关于c++ - VC++中通过A类函数指针调用B类成员函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27877107/

相关文章:

C 结构和指针混淆

c++ - 高度优化的矩阵乘法代码的 MSVC 和 GCC 之间的性能差异

c - 指向嵌套结构的指针

c - 评估 p && *p++

winapi - 如何使用动态布局控件删除对话框窗口上的边框?

c++ - 在 Windows XP 中多次启动程序 + DLL 时出现问题?

c++ - Visual 2015 上的 std::get_time 不会在不正确的日期失败

c++ - 为什么某些编译器拒绝作为指针传递的匿名对象?

c++ - 使用 bitbakes 在 openEmbedded 环境下部署 Jenkins

c++ - CLI/C++ 如何存储超过 15 位的 float ?