纯虚函数的目的便是,父类不需要去实现,全部都是在子类中实现,有纯虚函数的话,就是抽象类,而且子类必须重写这个纯虚函数。可见以下代码:
#include<iostream>
using namespace std;
class ami {
public:
virtual void eat() = 0; // 纯虚函数,有纯虚函数的便是抽象类
};
class cat : public ami {
public:
virtual void eat(){
cout << "猫猫吃东西" << endl;
}
};
int main() {
cat a;
a.eat();
return 0;
}
虚析构的话,顾名思义便是析构函数上面也有一个virtual关键字,我们先看下没有virtual关键字的情况:
#include<iostream>
using namespace std;
class class1 {
public:
class1(){}
~class1(){
cout << "class1类销毁了" << endl;
}
};
class class2 :public class1 {
public:
class2() :Value(NULL) {
Value = new int(10);
}
~class2() {
cout << "class2类销毁了" << endl;
delete Value;
}
int* Value;
};
int main() {
class1* b = new class2();
delete b;
return 0;
}
输出结果是 父类被销毁了,但是这种会导致内存泄漏。下面便是虚析构的应用,这样就可以避免内存泄漏的情况了
#include<iostream>
using namespace std;
class class1 {
public:
class1(){}
virtual ~class1(){
cout << "class1类销毁了" << endl;
}
};
class class2 :public class1 {
public:
class2() :Value(NULL) {
Value = new int(10);
}
~class2() {
cout << "class2类销毁了" << endl;
delete Value;
}
int* Value;
};
int main() {
class1* b = new class2();
delete b;
return 0;
}
输出结果显示,两个类均运行了析构函数,成功销毁了对应内容。
下面是纯虚析构的实现,也可以达到同样的结果,两个类也是均运行了析构函数,销毁了对应内容:
#include<iostream>
using namespace std;
class class1 {
public:
class1(){}
virtual ~class1() = 0;
};
class1::~class1() {
cout << "class1类销毁了" << endl;
}
class class2 :public class1 {
public:
class2() :Value(NULL) {
Value = new int(10);
}
~class2() {
cout << "class2类销毁了" << endl;
delete Value;
}
int* Value;
};
int main() {
class1* b = new class2();
delete b;
return 0;
}