C++实验2 继承和多态(二)

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的析构函数。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值