C++面向对象的动态绑定---虚函数的使用

本文是一个C++动态绑定(多态性)的实例,并给出了强制调用某一对象函数的方法(暂时取消动态绑定)

注意,直到运行时基类指定才能确定指向的对象

#include <iostream>
using namespace std;

class base_class
{
public:
    virtual int print(){ cout << "This is base class\n"; return 0; }
};

class derived_class :public base_class
{
public:
    virtual int print(){ cout << "this is derived class\n"; return 0; }
};
int main()
{
    base_class *p = new base_class();
    p->print();
    p = new derived_class();
    p->base_class::print();//覆盖虚函数机制并强制函数调用使用虚函数的特定版
    p->print();
    return 0;
}

 

posted @ 2015-03-14 17:00  lishuai0214  阅读(161)  评论(0编辑  收藏  举报