C++之private虚函数

一般我们说虚函数,它的访问级别都是public的,用类对象可以直接调用,这样就可以实现运行时的类型绑定,那如果我们将虚函数私有化会出现什么情况呢?

我们先来看一个非虚函数私有化的例子

class Base
{
private:
    void PrintClassName ()
    {
        cout<<"Base"<<endl;
    }
public:
    void print()
    {
        PrintClassName();
    }
};

class Derived : public Base
{
private:
    void PrintClassName()
    {
        cout<<"Derived"<<endl;
    }
};

在main函数里产生一个Derived的对象d,然后调用print()函数,即d.print(),结果输出的却是Base,print()函数没有调用子类的PrintClassName函数,而是调用父类的PrintClassName函数,原来是由于PrintClassName函数不是虚函数之故,所以Base的print()函数调用PrintClassName()函数是在编译时就已经绑定了,而不是运行期绑定。

下面我们让PrintClassName()函数变成虚函数再执行,就可以看到输出的类名为子类的名称,即Derived。

那么我们有没有办法调用私有的虚函数呢?当然是有的,不管公有还是私有,只要是虚函数,它的函数地址都会放在虚函数表vftable中,只要我们找到虚函数表中存放的PrintClassName()函数的地址,我们就可以直接调用,前提是你必须对C++类对象的内存布局要熟悉,代码如下,这样也输出Derived,与前面效果相同

int _tmain(int argc, _TCHAR* argv[])
{
    
    Derived d;
    //d.print();
    typedef void (*Fun)();
    Fun pFun = NULL;
    pFun = (Fun)*((int *)(*(int *)&d + 0) + 0);
    pFun();

    getchar();
    return 0;
}
posted @ 2012-08-08 21:55  venow  阅读(7515)  评论(3编辑  收藏  举报