c++ - 如何通过接口(interface)存储成员函数指针

标签 c++ class inheritance function-pointers

我会创建一个这样的界面:

class IMother {
public:
  // This getter return a map which contains a member functer pointer
  virtual map<string, void (IMother::*)()> getMap() const = 0;
  virtual ~IModule() {};
};

然后,创建一个子节点并覆盖getter以返回一个只包含Child_1成员函数指针的映射

class Child_1 : public IMother {
private:
  map<string, void (Child1::*)(int)> _map;

public:
  void do_something_1(int a) {
     // Something...
  }

  void do_something_2(int a) {
   // Something...
  }

  virtual map<string, void (Child1::*)(int)> getMap() {
     _map["do_1"] = &do_something_1;
     _map["do_2"] = &do_something_2;
     return _map;
  }

我认为我能够让它发挥作用,因为在我看来,我认为 Child1 是 IMother,所以我有权这样写,但我不能..

int main() {
   IMother *mother = new Child_1;

   // I don't know how run a method through a map
   mother->getMap["do_1"](42); // Not seem to work
   return 0;
}

有没有办法通过接口(interface)存储成员函数指针?

最佳答案

这里有几个问题:

  1. 首先,指向成员的指针赋值不正确:

    这个:

    _map["do_1"] = &do_something_1;
    _map["do_2"] = &do_something_2;
    

    应该是:

    _map["do_1"] = &Child1::do_something_1;
    _map["do_2"] = &Child1::do_something_2;
    
  2. 其次,IMother 和 Child1 上 getMap() 的返回类型不同,因为一个不接受参数并且是指向 IMother 成员的指针,而另一个接受 int 并且是指向 Child1 成员的指针。这两个差异导致 C++ 中的返回类型不同。

    妈妈:

    map<string, void (IMother::*)()>  
    

    child 1:

    map<string, void (Child1::*)(int)>
    

    由于返回类型不同,Child1 没有重载IMother 中定义的所有纯虚函数,因此不能实例化Child1 的实例。

  3. 第三,你的成员函数调用不正确。成员函数在调用之前仍然需要提供“成员”。例如

    class SomeClass;
    typedef void (SomeClass::* SomeClassFunction)(void);
    
    void Invoke(SomeClass *pClass, SomeClassFunction funcptr) {
        (pClass->*funcptr)(); 
    };
    

话虽如此,我还是会看一下 STL 功能 header 。 STL 函数库将允许您编写以下内容并在以后以比内置 C++ 语法更简单的语法调用它们:

typedef std::function<float (float)> MyFuncType;

map<sting, MyFuncType> myFuncs;
myFuncs["myCustomSin"] = &SomeClass::SomeCustomSinFunc;
myFuncs["cSin"] = &sin;

关于c++ - 如何通过接口(interface)存储成员函数指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9392451/

相关文章:

C++字符串模板库

c# - 如何在 visual studio 2015/中创建 C# 类图

c - 为什么C不支持继承?

c++ - 避免两阶段初始化

c++ - CUDA 计算后数组中的重复值

c++ - 用户定义类中的 Bool 作为函数 c++ 出现问题

c++ - 点云库的多重继承与单继承限制

java继承: distinguish between types of inherited classes

c++ - sizeof(int(123)) 是什么意思?

javascript - 在 TypeScript 中隐式扩展 JavaScript 类属性