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

标签 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; 
}

这会返回错误:

[Error] invalid cast from type 'int ()(int)' to type 'int (x::)(int)'

最佳答案

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; 
}

关于c++ - 类非静态方法指向全局函数的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40299888/

相关文章:

c++ - 只是想调用一个库的函数

c++ - 在另一个字符串中查找字符串的所有实例

用于无线传感器网络的 C++

c++ - "int* ptr = int()"值初始化如何不非法?

c++ auto type signed to/from unsigned 转换

c++ - 使用 boost::hana 过滤具有类型的列表

python - 使用 python 扩展 C++ 应用程序

C char指针动态分配——分配一个未知长度的值

c - 用户定义函数返回 0,即使不应该返回 0

c++ - 可移植浮点变量模板