指向全局函数的类非静态方法指针

时间:2016-10-28 07:11:19

标签: c++ pointers c++14

我试图将类方法指向全局函数,我已经看过this
但是如果没有实例我怎么做呢?

考虑一下:

class x
{
    public:
        int(x::*GetVal)(int);
};

int RtX(int a)
{
    return a * 4;
}

// declaration
int(x::*GetVal)(int) = (int(x::*)(int))&::Rtx; // :: global? // error

int main()
{
    x a;
    cout << (a.*GetVal)(4) << endl; 
}

这会返回错误:

  

[错误]来自类型&#39; int()(int)&#39;输入&#39; int   (X :: )(INT)&#39;

2 个答案:

答案 0 :(得分:1)

x::GetX是指向成员的指针。这些是非常复杂的野兽,你不能让它们指向非成员函数。以下代码将起作用:

#include <iostream>

int RtX(int a)   // Global non-member function
{
    return a * 4;
}

class x
{
    public:

        int(x::*GetVal)(int);

        // This is an instance member function which acts as a proxy and calls the
        // the global function
        int RtX(int a) { return ::RtX(a); }
};


int main()
{
    x a;
    a.GetVal =&x.RtX;  // Assign the member variable.  Could do this in the
                       // constructor.  **NOTE** No casts!
    std::cout << (a.*GetVal)(4) << std::endl; 
}

如果在处理函数指针和指向成员函数的指针时发现自己达到了强制转换,停止 - 你几乎肯定做错了,虽然它会编译,但它是很可能不会正常运行。

或者,如评论中所述,使用std::function

#include <iostream>
#include <functional>

int RtX(int a)
{
    return a * 4;
}

class x
{
public:
    std::function<int(int)> GetVal;

    // Initialize GetVal in the constructor.
    x() : GetVal(RtX) 
    {}

    // Alternatively, you can initialize the variable in with a default
    // initialization.  You can also declare the member const if you don't want to 
    // change it later.

    const std::function<int(int)> gv = RtX;

    /*
};

int main()
{
    x a;
    std::cout << a.GetVal(4) << std::endl; 
}

答案 1 :(得分:1)

非静态成员函数需要一个实例才能被调用。您可以考虑使用静态函数成员,如果您还使用std::function,则可能会得到一个简单的代码来分配您的成员函数而不使用实例:

#include <iostream>
#include <functional>

int RtX(int a)
{
    return a * 4;
}

class x
{
public:
    static std::function<int(int)> GetVal;
};

std::function<int(int)> x::GetVal = RtX;

int main()
{
    x a;
    std::cout << (a.GetVal)(4) << std::endl;
}