看下面的例子,使用虚函数的用意。
class animal
{
public :
animal(){};
void run()
{
cout<< “animal run”;
}
};
class dog : public animal
{
public :
dog(){};
void run()
{
cout<< ”dog run“;
}
};
class cat : public animal
{
public :
cat(){};
void run()
{
cout<< ”cat run“;
}
};
void main()
{
animal* ani;
ani = new dog();
ani->run();
ani = new cat();
ani->run();
}
输出结果都是:animal run,没有调用各派生类的run函数,虚函数解决这一问题。
|
class animal
{
public :
animal(){};
virtual void run()
{
cout << "animal run";
}
};
class dog: public animal
{
public :
dog(){};
void run()
{
cout << "dog run";
}
};
class cat: public animal
{
public :
cat(){};
void run()
{
cout << "cat run";
}
};
void main()
{
ani = new dog();
ani->run();
ani = new cat();
ani->run();
}
输出结果为:dog run cat run,若animal有很多派生类,则只声明一个animal指针即可,虚函数的作用明显体现。
|