简体   繁体   English

C ++非静态函数作为变量

[英]C++ Non static functions as variables

   class manip{
public:
    int t;
    manip(int tom){
        t = tom;
    }
    int sub(int val){
        return t - val;
    }
    int add(int val){
        return t + val;
    }
    int perform(int(manip::*key)(int), int val){
        return (this->*key)(val);
    }
};

int main() {
    manip g(5);
    cout << g.perform(&manip::add, 9) << ":" << g.perform(&manip::sub, 9);

(This is just a simplified version of a problem im trying to solve in a larger piece of code) (这只是我试图在更大的代码段中解决的问题的简化版本)

the problem lies here 问题出在这里

    int(b::*func)(int) = b::add;

    int c = func(2);

this gives me a syntax error on the second line (because i have no reference to the "this" data). 这在第二行给了我一个语法错误(因为我没有引用“ this”数据)。 How do i change it so that the function being called isnt b::add but rather inst.add. 我如何更改它,以便被调用的函数不是b :: add而是inst.add。

Edit : Posted a working version of the code. 编辑:张贴了代码的工作版本。 Thanks Speed8ump 谢谢Speed8ump

in your example 'func' is a member function pointer. 在您的示例中,“ func”是成员函数指针。 It must be used on an instance of the data type it is a member of: 它必须数据类型的实例可使用它的成员:

int c = (inst.*func)(2);

You need to give a parameter pointing to the struct (or aA). 您需要提供一个指向结构(或aA)的参数。

int main(){
    b inst(5)
    int(b::*func)(int, struct b*) = b::add;
    int c = func(2, &inst);
}

int add(int a, struct b* ptr){
    return a + ptr->aA;
}

If your compiler is new enough you can avoid function pointers and use std::function instead 如果您的编译器足够新,则可以避免使用函数指针,而应使用std :: function代替

 int(b::*func)(int) = b::add;

becomes 变成

#include <functional>
#include <iostream>
 class manip{
public:
    int t;
    manip(int tom){
        t = tom;
    }
    int sub(int val){
        return t - val;
    }
    int add(int val){
        return t + val;
    }
    int perform(std::function<int(manip*,int)>f, int val){
        return f(this, val);
    }
};

int main() {
    manip g(5);
    std::cout << g.perform(&manip::add, 9) << ":" << g.perform(&manip::sub, 9);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM