关于继承的多态
#include<iostream>
using namespace std;
class Animal { public: Animal(){}
Animal(int weight, int height){}
void eat(){ cout << "animal eat" << endl; }
void sleep(){ cout << "animal sleep" << endl; }
virtual void breath(){ cout << "animal breath" << endl; }
~Animal(){}; };
class Fish:public Animal { public: Fish() :Animal(40, 40){}
void breath() { cout << "Fish bubble" << endl; }
~Fish(){}; };
int main(){
/*Animal *An;
Fish fh;
An = &fh;//将Fish类的地址赋给An之后,但An->breath()调用的确是父类的breath*/
Animal *An=new Fish(); 此处将引起多态
if (An != NULL){ delete An; return 0; }
//An->breath();
//fh.breath();
system("pause"); }
允许将子类类型的指针赋值给父类类型的指针。
子类的指针赋给父类时,若基类中的同名函数未能声明为虚函数,若仍用父类的指针指向同名函数,编译器会调用父类中的函数,此时会引起多态。