【问题标题】:Passing member function to function pointer将成员函数传递给函数指针
【发布时间】:2010-11-30 04:14:44
【问题描述】:

我必须将成员函数的函数指针传递给另一个类。我无法编译它,并且出现“对 classB::classB(classA::*)(std::shared_ptr) 的未定义引用”错误。有人可以帮我解决这个问题吗?

谢谢。

classA{
  string functionA(share_ptr<int>);
  void functionB(){
     classB* ptr = new classB(&classA::functionA);
  }
}

//in other .h file
classA; //forward declaration

classB{
  classB(string (classA::*funcPtr)(shared_ptr<int>); //constructor
}

【问题讨论】:

  • 我明白了……原来是正确的语法……只是我在再次编译之前没有清理一些旧文件……浪费了我的时间……
  • 一件事是您的构造函数缺少右括号。此外,如果您也发布您的 .cpp 文件会很有帮助,因为标头没有显示 classB 构造函数的实现。
  • -1 问题中的信息不正确且不完整。该代码不是您的实际代码。它甚至不应该编译。并且提供的代码还不够完整,无法说明您的链接错误源于什么。

标签: c++


【解决方案1】:

我正在写的代码:

classA{
  string functionA(share_ptr<int>);
  void functionB(){
     classB* ptr = new classB(&classA::functionA);
  }
}

这里:

  • share_ptr 应该是shared_ptr

  • 类定义末尾缺少分号。

那么,

//in other .h file
classA; //forward declaration

classB{
  classB(string (classA::*funcPtr)(shared_ptr<int>); //constructor
}

这里:

  • 有三个左括号(,但只有两个右括号)

  • 类定义末尾缺少分号。

您询问的是链接错误,但您的代码甚至不应该编译。

当您说“我无法编译它”时,这似乎是正确的。

当您随后声明“我得到 [未定义的引用...]”时,这是一个谜:对于您显然使用的工具链,当编译失败时不应调用链接器。

总之,这个问题包含一些不正确的信息和任何答案(例如您尚未定义函数的假设,或者您在某处定义但忘记链接的假设,或者您的假设)重新报告构建其他代码而不是代码的错误,等等)将是纯粹的猜测。

请发一个完整的小程序,编译并说明链接错误。

干杯,

【讨论】:

    【解决方案2】:

    只是为了咯咯笑,即使你说它是为你编译的,也要回答这个问题......

    // In a.hpp
    #include "b.hpp" // you need to include this because you will not
                     // be able to call B's constructor in your functionB() method
    
    class A
    {
    public:
      string functionA ( shared_ptr<int> ); // IIRC, needs to be public to call it
                                            // from B's constructor.
    
      // can be public/protected/private depending on where it's called ...
      void functionB () {
        B * ptrB = new B ( &A::functionA );
      }
    };
    

    // In b.hpp
    
    // Forward declare class A
    class A;
    // To make the constructor of B cleaner, use a typedef.
    typedef string (A::*IntPtrToStrFn) ( shared_ptr<int> );
    
    class B
    {
    public:
      B ( IntPtrToStrFn fnptr );
    };
    

    就样式和代码可读性而言,这太可怕了 - 将两个类联系在一起并散发出代码异味。需要查看某种适配器类或其他设计模式以使这两个类协同工作。

    【讨论】:

      【解决方案3】:

      从表面上看,这只是一个前向声明问题。尝试像之前那样声明classA::functionB,然后在classB 的定义之后定义classA::functionB

      【讨论】:

        猜你喜欢
        • 2012-08-01
        • 2021-11-29
        • 2017-05-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-03-22
        相关资源
        最近更新 更多