书上说当基类指针指向带有需函数的派生类时,会出现覆盖现象。可是下面的pt1=&cat1中其中cat并未带有需函数,为社么同样出现了覆盖现象?
#include<iostream>
using namespace std;
class Pet
{
public: virtual void Speak()
{
cout<<"How dose a pet speak?"<<endl;
}
};
class Cat:public Pet
{
public:
void Speak()
{
cout<<"miaomiao!"<<endl;
}
};
class Dog:public Pet
{
public:
void Speak()
{
cout<<"wangwang!"<<endl;
}
};
void main()
{
Pet *pt1,*pt2,*pt3,obj;
Dog dog1;
Cat cat1;
obj=dog1; //子类对象赋给基类对象,只能当做基类对象来使用
obj.Speak();
pt1=&cat1; //问题
pt1->Speak();
pt2=new Cat;
pt2->Speak();
pt3=new Dog;
pt3->Speak();
Pet &p4=cat1;
p4.Speak();
}