【问题标题】:Calling a member function using function pointers from another class's instance使用来自另一个类实例的函数指针调用成员函数
【发布时间】:2013-01-15 07:00:49
【问题描述】:
#include<iostream>
#include<conio.h>
using namespace std;
class Base;
typedef void (Base::*function)();
class Base
{
public:
    function f;
    Base()
    {
        cout<<"Base Class constructor"<<endl;
    }
    virtual void g()=0;
    virtual void h()=0;
};
class Der:public Base
{
public:
    Der():Base()
    {
        cout<<"Derived Class Constructor"<<endl;
        f=(function)(&Der::g);
    }
    void g()
    {
        cout<<endl;
        cout<<"Function g in Derived class"<<endl;
    }
    void h()
    {
        cout<<"Function h in Derived class"<<endl;
    }
};
class Handler
{
    Base *b;
public:
    Handler(Base *base):b(base)
    {
    }
    void CallFunction()
    {
        cout<<"CallFunction in Handler"<<endl;
        (b->*f)();
    }
};
int main()
{
    Base *b =new Der();
    Handler h(b);
    h.CallFunction();
    getch();
}

尝试使用基类中声明的函数指针调用派生类中的成员函数时出现错误。函数指针被声明为 public 并且实际上被另一个类 Handler 使用。我在这段代码中使用了不安全的类型转换。 (函数)(&Der::g)。有什么办法可以避免吗?

【问题讨论】:

  • stackoverflow.com/questions/6754799/… - 请改用Base::g,您的演员阵容无效。
  • 函数 f != 指针。所以 *f 是不正确的。
  • @Laurence 感谢您的回复。但是为什么 f 不是指针。不是函数指针吗。对不起,如果这是一个愚蠢的问题。
  • 抱歉,没有正确读取代码。

标签: c++ inheritance function-pointers


【解决方案1】:

f 似乎不在Handler::CallFunction 的范围内。我猜你的意思是使用b 调用b-&gt;f 作为this,因为它是(b-&gt;*(b-&gt;f))()。当我进行此更改时,您的代码会编译并打印出一些正常的东西。

【讨论】:

  • 感谢您的回复。它按我想要的方式工作。但我不明白为什么它早些时候给了我错误。既然 f 是公共成员,为什么我不能在 Handler 中访问它?当我写 (b->*f)() 时发生了什么?
  • @sajas:成员指针语法总是令人困惑。在Handler 中,成员的名称是b-&gt;f,就像任何其他成员变量一样。 (更长的版本是function bf = b-&gt;f; b-&gt;*bf();。)b-&gt;* 序列表示“调用 b 的成员函数之一”,但“*”后面的东西必须从 Handler 的角度命名,而不是从 b 的角度命名- 那个箭头没有“到达内部”b.
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-09
  • 1970-01-01
  • 1970-01-01
  • 2011-03-10
  • 2022-08-09
相关资源
最近更新 更多