简体   繁体   English

类成员函数变量指向另一个类函数成员

[英]class member function variable pointing to another class function member

can you please explain me why this code shows nothing except for the last std::cout line in main()? 你可以解释一下为什么除了main()中的最后一个std :: cout行之外,这段代码什么都没有显示? Checked through similar threads on stackoverflow.com, was not able to connect them to mine, is this pointing legal at all? 通过stackoverflow.com上的类似线程检查,无法将它们连接到我的,这是否合法? I try to set a function pointer of a class to another class function: 我尝试将类的函数指针设置为另一个类函数:

#include <iostream>

class container;

class one {
public:
one() 
    { 
        eventsHandler = NULL; 
    };
~one() {}; 

void (container::*eventsHandler)();
};

class container {
public:
    container() 
    { 
        zone = new one;
        zone->eventsHandler = &container::events;
    };
    ~container()
    { 
        delete zone; 
    };

    one *zone;
    void events()
    {
        std::cout << "event handler is on..." << std::endl;
    };
};

int main()
{
    container *test = new container;
    test->zone->eventsHandler;

    std::cout << "just checker..." << std::endl;
    delete test;

    system("pause");
};

You should use operator->* for calling the member function pointer, and assign test as the object which will be called on, 您应该使用operator->*来调用成员函数指针,并将test指定为将被调用的对象,

(test->*test->zone->eventsHandler)();

or more clear, 或者更清楚,

(test->*(test->zone->eventsHandler))();

LIVE 生活

你必须在第38行实际调用函数指针,如下所示:

(test->*test->zone->eventsHandler)();

You need to provide an object to call a pointer to memeber function: 您需要提供一个对象来调用指向memeber函数的指针:

container *test = new container;
(test->*test->zone->eventsHandler)();

Here, test is the object, test->zone->eventsHandler is the pointer to member function that you have saved, and operator->* joins them. 这里, test是对象, test->zone->eventsHandler是你保存的成员函数的指针, operator->*加入它们。

So, it is very much like any other member function; 所以,它与任何其他成员函数非常相似; however, you can switch which objects to call a member on: 但是,您可以切换哪些对象来调用成员:

container *first = new container;
container *second = new container;
(first->*second->zone->eventsHandler)();
// both pointers point to the same function
std::cout << (first->zone->eventsHandler == second->zone->eventsHandler) << std::endl;

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

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