1、多态性综合运用
1.1一般多态性函数:输入输出参数完全一样,在父类中添加virtual;
- 有继承关系
- 子类重写父类中的虚函数
#include<iostream>
using namespace std;
class Animal
{
public:
virtual void speak()
{
cout<<"动物在叫"<<endl;
}
};
class Cat:public Animal
{
public:
void speak()
{
cout<<"猫叫"<<endl;
}
};
class Dog:public Animal
{
public:
void speak()
{
cout<<"狗叫"<<endl;
}
};
void DoSpeak(Animal& animal)
{
animal.speak();
}
void test()
{
Animal ani;
DoSpeak(ani);
Cat cat;
DoSpeak(cat);
Dog dog;
DoSpeak(dog);
}
int main(){
test();
}
1.2特殊多态性函数:输入或输出参数在子类中是父类的指针或基类的引用,在子类中对于的是子类的指针或子类的引用;
1.3析构函数的多态性;
class Animal
{
public:
Animal() {
cout << "创建Animal类\n";
}
~Animal() {
cout << "销毁Animal类\n";
}
virtual void speak()
{
cout<<"动物在叫"<<endl;
}
};
class Cat:public Animal
{
public:
Cat() {
p = new int(0);
cout << "创建Cat类\n";
}
~Cat() {
cout << "销毁Cat类\n";
delete p;
}
void speak()
{
cout<<"猫叫"<<endl;
}
private:
int *p;
};
class Dog:public Animal
{
public:
void speak()
{
cout<<"狗叫"<<endl;
}
Dog(){
p = new int(0);
cout << "创建Dog类\n";
}
~Dog() {
cout << "销毁Dog类\n";
delete p;
}
private:
int *p;
};
void test2(){
Animal* pDog = new Dog;
pDog->speak();
delete pDog;
}
int main(){
test2();
}
Dog的析构函数没有调用,Dog的构造函数申请的空间泄漏了。
改成虚析构函数能够有效的防止这种情况的出现。
Animal的析构函数声明为虚析构函数,成功的通过基类指针调用了Dog的析构函数。