这是CSDN上一个我觉得对C++初学者了解虚函数一处很好的题目。
#include <iostream>
using namespace std;
class CA
{
public:
void f(){cout << "CA f()" << endl;}
virtual void ff(){cout << "CA ff()" << endl;f();}
};
class CB : public CA
{
public :
virtual void f(){cout << "CB f()" << endl;}
void ff(){cout << "CB ff()" << endl;f();CA::ff();}
};
class CC : public CB
{
public:
virtual void f(){cout << "C f()" << endl;}
};
int main()
{
CB b;
CA *ap = &b;
CC c;
CB &br = c;
CB *bp = &c;
ap->f();
cout<<endl;
b.f();
cout<<endl;
br.f();
cout<<endl;
bp->f();
cout<<endl;
ap->ff();
cout<<endl;
bp->ff();
cout<<endl;
return 0;
}
运行结果:
CA f()
CB f()
C f()
C f()
CB ff()
CB f()
CA ff()
CA f()
CB ff()
C f()
CA ff()
CA f()
分析:
两条原则:
(1)指针和引用均能实现多态。
(2)输出什么关键看“=”右边是否为虚函数。
如果CA类中的f()也为虚函数,即程序如下:
include <iostream> using namespace std; class CA { public: virtual void f(){cout << "CA f()" << endl;} virtual void ff(){cout << "CA ff()" << endl;f();} }; class CB : public CA { public : virtual void f(){cout << "CB f()" << endl;} void ff(){cout << "CB ff()" << endl;f();CA::ff();} }; class CC : public CB { public: virtual void f(){cout << "C f()" << endl;} }; int main() { CB b; CA *ap = &b; CC c; CB &br = c; CB *bp = &c; ap->f(); cout<<endl; b.f(); cout<<endl; br.f(); cout<<endl; bp->f(); cout<<endl; ap->ff(); cout<<endl; bp->ff(); cout<<endl; return 0; }
运行结果:
CB f()
CB f()
C f()
C f()
CB ff()
CB f()
CA ff()
CB f()
CB ff()
C f()
CA ff()
C f()
在C++中实现动态多态性需要三个条件:
(1)对象是从同一个类层次结构中的不同的类产生的;
(2)调用的函数是虚函数;
(3)通过基类指针或引用来调用虚函数。