纯虚函数
定义:virtual 函数返回值类型 函数名() = 0;
抽象类
类中有纯虚函数的类称为抽象类;抽象类无法实例化对象;抽象类的子类必须重写父类中的纯虚函数;
纯虚函数从定义的角度看,其实就是在虚函数的基础上去掉大括号,变为=0即可;
纯虚函数和抽象类代码解释如下:
#include<iostream>
using namespace std;
class Persion {//抽象类
public:
virtual void speek() = 0;//纯虚函数
};
class Teacher:public Persion {
public:
virtual void speek() {//Persion子类强制实现父类总的纯虚函数(Java中称为抽象函数)
cout << "老师会说话" << endl;
}
};
int main() {
//Persion p;//类中有纯虚函数的类为抽象类 ,不能直接实例化为对象
Teacher t = Teacher();
t.speek();
return 0;
}
虚析构和纯虚析构
虚析构不是不必须,只有当子类有成员存储开辟在堆区存储时,需要父类添加虚析构,这样当子类被回收时子类的析构函数才会调用;
虚析构代码解释如下:
#include<iostream>
using namespace std;
class Animal{
public:
Animal() {
cout << "Animal构造调用" << endl;
}
virtual void eat() {
cout << "动物会吃" << endl;
}
virtual ~Animal(){//虚析构,如果父类不添加虚析构,子类的析构函数不调用
cout << "Animal析构调用" << endl;
}
};
class Dog :public Animal {
public:
Dog(string name) {
cout << "Dog构造调用" << endl;
this->name = new string(name);
}
void eat() {
cout << "小狗吃骨头" << endl;
}
~Dog() {//父类如果不添加虚析构,此析构编译器不调用
if (name != NULL) {
delete name;
name = NULL;
}
cout << "Dog析构调用" << endl;
}
string * name;
};
int main() {
Animal* d2 = new Dog("藏獒");
d2->eat();
delete d2;
return 0;
}
纯虚析构需要声明也需要实现;声明了纯虚析构函数的类也是抽象类;
纯虚析构代码声明
virtual ~类名() = 0;//纯虚析构的声明
纯虚析构的代码阐述:
#include<iostream>
using namespace std;
class Animal{
public:
Animal() {
cout << "Animal构造调用" << endl;
}
virtual void eat() {
cout << "动物会吃" << endl;
}
//virtual ~Animal(){//虚析构,如果父类不添加虚析构,子类的析构函数不调用
// cout << "Animal虚析构调用" << endl;
//}
virtual ~Animal() = 0;//纯虚析构
};
Animal:: ~Animal() {//纯虚析构类外实现
cout << "Animal纯虚析构调用" << endl;
}
class Dog :public Animal {
public:
Dog(string name) {
cout << "Dog构造调用" << endl;
this->name = new string(name);
}
void eat() {
cout << "小狗吃骨头" << endl;
}
~Dog() {
if (name != NULL) {
delete name;
name = NULL;
}
cout << "Dog析构调用" << endl;
}
string * name;
};
int main() {
Animal* d2 = new Dog("藏獒");
d2->eat();
delete d2;
return 0;
}