zoukankan      html  css  js  c++  java
  • 一个调用问题

    在看项目代码时,发现有个调用,明明调用的函数基类的,搞不懂为什么会调用到派生类的,这是个虚函数,我想肯定是指针的问题,我又想到了是绑定时候的问题

    thrTransData::thrTransData()
    {
        m_spTimerFactory = NEWSP(TimerFactory);
    
        new std::thread(std::bind(&thrTransData::thread, this));
    };

    感觉这个this绑定的肯定是基类的指针啊,调用怎么会调用到派生类上面去,自己写个例子测试

    #include <iostream>
    #include <functional>
    using namespace std;
    
    class A{
    public:
        A();
        virtual void fun1(){};
        void fun2();
        std::function<void()> m_heh;
    };
    
    A::A()
    {
        m_heh = std::bind(&A::fun2, this);
    }
    
    void A::fun2()
    {
        fun1();
    }
    
    class B:public A
    {
    public:
        void fun1();
    
    private:
    
    };
    
    void B::fun1()
    {
        std::cout<<"hhe";
    }
    
    int main()
    {
        A* p = new B;
        p->m_heh();
        getchar();
        return 0;
    
    }

    调用的果然是派生类的fun1,我知道是这个绑定this指针的问题,但具体的还是不清楚,得看看c++内存模型这本书,大家对这本书评价都很高,到时得看看。

  • 相关阅读:
    (转)重识new
    【洛谷习题】连续自然数和
    【AHOI2005】约数研究
    【NOIP2003】麦森数
    康托展开
    【洛谷习题】南蛮图腾
    【洛谷习题】吃奶酪
    【NOIP2002】字串变换
    哈希表
    【NOIP2013】货车运输
  • 原文地址:https://www.cnblogs.com/zzyoucan/p/3705749.html
Copyright © 2011-2022 走看看