• C++中虚函数指针问题


    《Inside C++ model》中已经解释的很详细了,这篇文章http://blog.csdn.net/heavendai/article/details/7008066,解释了如何调用找出虚函数的地址并调用,后来我发现其实取出的函数指针并不能应用,因为没传递函数指针,所以如果虚函数中对成员变量的访问将会是未定义的行为,比较危险。我来实现一个比较实用的基类指针,用来指向虚函数,下面是demo:

    #include <iostream>
    
    using namespace std;
    
    class Base {
    public:
        typedef void (Base::*handler_ptr)();
        Base():x(3), y(4){}
    
        virtual void f() { cout << "Base::f" << endl; cout << "my x is " << x << endl;}
    
        virtual void g() { cout << "Base::g" << endl; }
    
        virtual void h() { cout << "Base::h" << endl; }
    
        int x;
        int y;
        handler_ptr ptr_;
    };
    
    class Derive : public Base
    {
    public:
        virtual void f() { cout << "Derive::f" << endl << "my x is " << x << endl;}
        virtual void h() { cout << "Derive::h" << endl << "my y is " << y << endl;}
        void test_h()
        {
            ptr_ = &Base::h;
            (this->*ptr_)(); 
        }
    };
    
    
    typedef void (Base::*fun_ptr)();
    
    int main()
    {
        Base b;
        fun_ptr pfun_my = &Base::f;
        (b.*pfun_my)();
        Derive d;
        (d.*pfun_my)();
        d.test_h();
        return 0;
    }

    这样,x和y的访问是没有问题的。

    输出为

    Base::f
    my x is 3
    Derive::f
    my x is 3
    Derive::h
    my y is 4
  • 相关阅读:
    httpclient_1
    jmeter java请求
    fiddler监听手机
    lr文件的作用?
    配置源
    数据结构--堆
    A + B Problem II 高精度
    最小生成树(kruskal算法)+prim算法
    P3371 【模板】单源最短路径(弱化版)
    P3368 【模板】树状数组 2(实现区间修改&单点查询)
  • 原文地址:https://www.cnblogs.com/zhangyonghugo/p/2613647.html
Copyright © 2020-2023  润新知