zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    php 中的 Output Control 函数
    web安全知识
    php写一个web五子棋
    实现一个web服务器, 支持php
    字节序
    TinyHTTPd源码分析
    linux 管道通信
    linux网络编程
    微信公众号开发-静默授权实现消息推送(微服务方式)
    初学 Nginx
  • 原文地址:https://www.cnblogs.com/zhangyonghugo/p/2613647.html
Copyright © 2011-2022 走看看