父类的成员函数的函数指针 [英] Function pointers to member functions of a parent class

查看:272
本文介绍了父类的成员函数的函数指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在试图理解C ++中的函数指针,以便我可以在我的一个项目中成功使用它们。我遇到了一个逻辑问题。假设我们有两个类:父类和继承父类的子类。

  class Parent {
... other stuff
void(Parent :: * ptr2func)();
... other stuff
};

然后我们有一个子类:

  class Child:public Parent {
... other stuff
void afunc();
... other stuff
};

我想将父类的指针连接到 afunc 子类的函数。在子类的构造函数中,我尝试这样做:

  Child :: Child b {
ptr2func =& Child :: afunc;
}

这返回了一个预期的错误:
无法转换 void(Child :: *)() void(Parent :: *)()
$ b

我害怕这样的事情会发生。但是我该如何解决呢?我不能链接一个函数指针到父类的成员函数到子类的成员函数?正如你可以理解,我试图通过函数指针实现多态性,只是为了试验和不使用虚拟函数。我导致相信这是可能的。我的错误是什么?

解决方案

A void(Parent :: *)()接受父类型的对象。函数 Child :: afunc 需要一个类型为Child的对象。因此,将指针转换为 void(Parent :: *)()将允许无效的调用。



函数指针不能真正用来实现多态性。不使用virtual来实现多态的传统方法是使用常规函数指针:

  struct MyBaseClass 
{
void(* function)(MyBaseClass * this_pointer);
};


I have been trying to understand function pointers in C++ so that I can successfully use them in one of my projects. I am running into a logic problem though. Say we have two classes: a parent class and a child class which inherits the parent class.

class Parent{
    ...other stuff
   void (Parent::*ptr2func) ();
    ...other stuff
};

Then we have a child class:

class Child : public Parent{
       ...other stuff
       void afunc();
       ...other stuff
};

I wanted to connect the pointer of the parent class to the afunc() function of the child class. In the constructor of the child class is where I tried to do it like so:

  Child::Child()
  {
    ptr2func = &Child::afunc;
  }

This returned an expected error: cannot convert void (Child::*)() to void (Parent::*)() in assignment.

I was afraid that such a thing would happen. But how do I get over this? Can't I link a function pointer to a member function of a parent class to a member function of the child class? As you can understand I am trying to achieve polymorphism through function pointers just for experimenting and without using virtual functions. I was lead to believe that this is possible. What is my mistake? Or is it just not possible?

解决方案

A void (Parent::*)() takes an object of type Parent. The function Child::afunc requires an object of type Child. Converting the pointer to void (Parent::*)() would therefore allow for an invalid call.

Member function pointers can't really be used to implement polymorphism. The traditional way to implement polymorphism without using virtual is to use regular function pointers:

struct MyBaseClass
{
    void (*function)(MyBaseClass* this_pointer);
};

这篇关于父类的成员函数的函数指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆