绑定和虚函数重载

绑定和虚函数重载

本文介绍了Boost ::绑定和虚函数重载:为什么他们工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了一些代码,害怕它不会工作 - 所以我写了一个原型:

I wrote some code and got scared that it will not work - so I wrote a prototype:

#include <boost/function.hpp>
#include <boost/bind.hpp>
#include <iostream>

class base {
private:
    boost::function<void (int)> action;
protected:
    virtual void onDataBaseReady(int i) { std::cout << i << std::endl; }
public:
    void call() {
        action(10);
    }

    base() {
        action = boost::bind(&base::onDataBaseReady, this, _1);
    }
};

class child : public base {
protected:
    virtual void onDataBaseReady(int i) { std::cout << i+10 << std::endl; }
};

int main()
{
    static child c;
    c.call();
    std::cin.get();
    return 0;
}

(输出 20 )。但为什么?我在VS2010下测试,并想知道它是否可以跨平台工作(例如编译在GCC下)?

that compiles and works. (outputs 20). But Why? Also I tested under VS2010 and wonder if it would work across platforms (say compiled under GCC)?

主要 action = boost :: bind ; base :: onDataBaseReady,this,_1); 吓跑我 - 我们说& base :: ...

Mainly action = boost::bind(&base::onDataBaseReady, this, _1); scares me - we say &base::...

推荐答案

指向虚拟方法的指针 virtual 函数查找。

A pointer to a virtual method does a virtual function lookup when called.

#include <iostream>
#include <memory>

struct base {
  virtual void foo() { std::cout << "base\n"; }
  virtual ~base() {}
};

struct derived:base {
  void foo() override final { std::cout << "derived\n"; }
};

int main() {
  void (base::*mem_ptr)() = &base::foo;
  std::unique_ptr<base> d( new derived() );
  base* b = d.get();
  (b->*mem_ptr)();
}

所以,它只是工作。成员函数指针(this-> *& base :: foo)()与完全限定函数调用不一样 this- > base :: foo()。第一种是存储调用 this-> foo() foo 部分的方法,方法跳过虚拟方法查找并直接调用 base :: foo

so, it "just works". The member function pointer (this->*&base::foo)() is not the same as a fully qualified function call this->base::foo(). The first is a way to store the foo part of calling this->foo(), the second is a way to skip virtual method lookup and directly call base::foo.

这篇关于Boost ::绑定和虚函数重载:为什么他们工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-24 17:39