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