繁体   English   中英

如何在std :: function中存储虚拟成员函数?

[英]How to store a virtual member function in std::function?

class foo
{
public:
    foo(void)
    {
        this->f = std::bind(&foo::doSomething, this);
    }

private:
    virtual void doSomething(void) { }

private:
    std::function<void(void)> f;
}

class bar : public foo
{
public:
    bar(void) { /* I have no idea what I have to */ }

private:
    virtual void doSomething(void) override { }
}

我想将覆盖的'doSomething'函数分配给'foo :: f'。 但我不知道如何分配重写的“ doSomething”功能。 还是我只写一些代码为每个类分配“ doSomething”功能?

class foo
{
public:
    foo(void)
    {
        this->f = std::bind(&foo::doSomething, this);
    }

private:
    virtual void doSomething(void) { }

private:
    std::function<void(void)> f;
}

class bar : public foo
{
public:
    bar(void) 
    {  
        this->f = std::bind(&bar::doSomething, this);
    }

private:
    virtual void doSomething(void) override { }
}

该代码是我对问题的回答。 但是我想我可以将虚拟函数自动分配给std :: function。

this->f = std::bind(&foo::doSomething, this);

这样很好。 通过指针或引用传递对象将允许它调用正确的虚函数。

暂无
暂无

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

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