编写一个哺乳动物类 Mammal,再由此派生出狗类 Dog,二者都声明 speak()成员函数,该函数在基类中被声明为虚函数。声明一个 Dog 类的对象,通过此对象调用speak 函数,观察运行结果。
#include <iostream>
using namespace std;
class Mammal{
public:
Mammal(){cout << "Constructor in Mammal.\n";}
virtual ~Mammal(){cout << "Destructor in Mammal.\n";}
virtual void speak(){
cout<<"Mammal speak!\n";
}
};
class Dog:public Mammal{
public:
Dog(){cout << "Constructor in Dog.\n";}
~Dog(){cout << "Destructor in Dog.\n";}
void speak(){cout << "Dog sound wang,wang,wang!\n";}
};
int main()
{
Mammal *m = new Dog;
m->speak(); //使用虚函数,根据指针指向的类型执行哪种方法
delete m;
return 0;
}