c++多态机制的实现

class A{
public:
virtual void f() { cout << "A::foo() is called" << endl;}
virtual void g() { cout << "A::g() is called" << endl;}
};

class B: public A{
public:
void f() { cout << "B::foo() is called" << endl;}
};

int main(){
A *a=new B();
a->f();
a->g();
B *b=new B();
b->f();
b->g();
b->A::f();
return 0;
}

定义一个函数为虚函数
1.如果该函数在子类中没有被覆盖,则在子类的虚函数表中存在两个相同的函数,访问时不能达到多态的效果
2.在子类中覆盖该函数,则调用时形成多态。

原文地址:https://www.cnblogs.com/noor/p/5585383.html