简体   繁体   English

带类的函数指针

[英]Function pointers with classes

I've been looking for a few days and at this point I assume that I'm not looking with the right criteria.Here's what I need to do我一直在寻找几天,此时我认为我没有按照正确的标准寻找。这是我需要做的

class AB
{
    public:
        std::function<void()>addr;
};

class BC
{
    public:
        void myTestFunc(std::string value)
        {
            std::cout << "AB::myTestFunc called: " << value << std::endl;
        }
};

int main(void)
{
    AB ob;
    BC obj2;

    ob.addr = std::bind(&obj2::myTestFunc, "");
    // so that i can call
    (ob.addr)("testing");

    return 0;
}

The problem is that I need to have a class that can allow instances of other classes its used to call a function on the "parent" or main class.问题是我需要一个类,该类可以允许其他类的实例用于调用“父类”或主类上的函数。 The actual arguments and functions are obviously different but I cannot get it to work with a class public function.实际参数和函数显然不同,但我无法让它与类公共函数一起使用。 I cannot make it static as each instance of the "child" class will be calling a separate function.我不能让它静态,因为“子”类的每个实例都将调用一个单独的函数。 Please tell me what I should be searching for and / or what I'm doing wrong.请告诉我我应该搜索什么和/或我做错了什么。

I believe this is where you're going.我相信这就是你要去的地方。

class AB
{
    public:
        std::function<void(std::string)>addr;
};

class BC
{
    public:
        void myTestFunc(std::string value)
        {
            std::cout << "AB::myTestFunc called: " << value << std::endl;
        }
};

int main(void)
{
    AB ob;
    BC ob2;
    std::string i = "testing";
    ob.addr = std::bind(&BC::myTestFunc, &ob2, i);
    ob.addr(i);

    return 0;
}

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

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