01:
#include<iostream>
using namespace std;
//制作饮品
class AbstactDrinking
{
public:
//煮水
virtual void Boil() = 0;
//冲泡
virtual void Brew() = 0;
//倒入水中
virtual void PourInCup() = 0;
//加入辅料
virtual void PutSomething() = 0;
//制作饮品
void makeDrink()
{
Boil();
Brew();
PourInCup();
PutSomething();
}
};
class Coffee : public AbstactDrinking
{
public:
//煮水
virtual void Boil()
{
cout << "煮水" << endl;
}
//冲泡
virtual void Brew()
{
cout << "冲泡" << endl;
}
//倒入水中
virtual void PourInCup()
{
cout << "倒入水中" << endl;
}
//加入辅料
virtual void PutSomething()
{
cout << "加入辅料" << endl;
}
};
//制作茶叶
class Tea : public AbstactDrinking
{
public:
//煮水
virtual void Boil()
{
cout << "煮水" << endl;
}
//冲泡
virtual void Brew()
{
cout << "冲泡" << endl;
}
//倒入水中
virtual void PourInCup()
{
cout << "倒入水中" << endl;
}
//加入辅料
virtual void PutSomething()
{
cout << "加入辅料" << endl;
}
};
//制作函数
void doWork(AbstactDrinking *abc) //AbstactDrinking *abc =new Coffee ---当测试函数传入参数时
{
abc->makeDrink();
delete abc; //释放
}
void test01()
{
//制作Coffee
doWork(new Coffee);
cout << "----------------" << endl;
doWork(new Tea);
}
int main()
{
test01();
return 0;
}
02:
总结:
1:虚析构或纯虚析构就是用来解决通过父类指针释放子类对象
2:如果子类中没有堆区数据,可以不写为虚析构或纯虚析构
3:拥有纯虚析构函数的类也属于抽象类
4:利用虚析构可以解决 父类指针释放子类对象时不干净的问题
5:纯虚析构–需要声明也需要具体实现
6:有了纯虚函数后 这个类也属于抽象类,无法实例化对象
7:父类指针在析构时候 不会调用子类中析构函数,导致如果子类有堆区属性,出现内存泄漏
/*
总结:
1:虚析构或纯虚析构就是用来解决通过父类指针释放子类对象
2:如果子类中没有堆区数据,可以不写为虚析构或纯虚析构
3:拥有纯虚析构函数的类也属于抽象类
*/
#include<iostream>
#include<string>
using namespace std;
class Animal
{
public :
//纯虚函数
Animal()
{
cout << "Animal构造函数调用" << endl;
}
//利用虚析构可以解决 父类指针释放子类对象时不干净的问题
/*virtual ~Animal()
{
cout << "Animal 析构函数的的调用" << endl;
}
*/
//纯虚析构--需要声明也需要具体实现
//有了纯虚函数后 这个类也属于抽象类,无法实例化对象
virtual ~Animal() = 0;
//纯虚函数
virtual void speak() = 0;
};
Animal::~Animal() //纯虚函数的具体实现
{
cout << "纯虚析构的调用 " << endl;
}
class Cat :public Animal
{
public :
Cat(string name)
{
cout << "Cat构造函数的调用" << endl;
m_Name = new string(name);
}
virtual void speak()
{
cout << *m_Name<<"小猫在说话 " << endl;
}
~Cat()
{
if (m_Name != NULL)
{
cout << "Cat析构函数调用" << endl;
delete m_Name;
m_Name = NULL;
}
}
string *m_Name;
};
void test01()
{
Animal* animal = new Cat("Tom");
animal->speak();
//父类指针在析构时候 不会调用子类中析构函数,导致如果子类有堆区属性,出现内存泄漏
delete animal;
}
int main()
{
test01();
return 0;
}