指向嵌套类中的成员函数的 C++ 指针

c++ pointer to member function from a nested class

本文关键字:成员 函数 C++ 指针 嵌套      更新时间:2023-10-16

我在嵌套类"Outer::Inner"中定义的指向"Outer"类的成员函数的指针有问题:

class Outer{
//class Inner;
class Inner{
    public:
        Inner(Outer& o){
        }
        int (Outer::*pf)(int);
};
public:
    Outer();
    ~Outer();
    int function(int a);
    Inner* i;
};
Outer::Outer(){
    i = new Inner( *this );
    i->pf= &Outer::function;
    (i->*pf)(2); //problem here!
};
Outer::~Outer(){
    delete i;
};
int Outer::function(int a){
    return 0;
};

如您所见,我想通过 Inner 类的指针调用该函数,但我得到一个错误:'pf' 未在此范围内声明。

正如错误所说,pf没有在该范围内声明。它是i的成员,可作为i->pf访问。大概,你想在this上调用它:

(this->*(i->pf))(2);
你需要

在某个Outer对象上调用函数,因为它是指向成员函数的指针。

看看你的代码,也许你需要这个

//-----------------vvv   <- argument
   (this->*(i->pf))(2);
//-^--------------^  <- these are important and they say something like
// "execute function `*(i->pf)` on `this` object"

2 个解决方案。

1:(指向非成员函数的指针)

class Outer{
class Inner{
    public:
        Inner(Outer& o){
        }
        int (*pf)(int);
};
public:
    Outer();
    ~Outer();
    static int function(int a);
    Inner* i;
};
Outer::Outer(){
    i = new Inner( *this );
    i->pf= &Outer::function;
    int j = (*(i->pf))(2); // now OK
};

2:(指向成员函数的指针,必须在某个实例上调用)

class Outer{
class Inner{
    public:
        Inner(Outer& o){
        }
        int (Outer::*pf)(int);
};
public:
    Outer();
    ~Outer();
    int function(int a);
    Inner* i;
};
Outer::Outer(){
    i = new Inner( *this );
    i->pf= &Outer::function;
    int j = (this->*(i->pf))(2); // now OK
};