虚函数
定义纯虚函数是为了实现一个接口,起到一个规范的作用,规范继承这个类的程序员必须实现这个函数。
一个类函数的调用并不是在编译时刻被确定的,而是在运行时刻被确定的。由于编写代码的时候并不能确定被调用的是基类的函数还是哪个派生类的函数,所以被成为“虚”函数。
虚析构函数
我们首先看一段代码
class animal
{
public:
animal()
{
cout << "animal类构造" << endl;
}
~animal()
{
cout << "animal类析构" << endl;
}
virtual void speak()
{
cout << "animal说话" << endl;
}
};
class cat :public animal
{
public:
string name;
cat(string _name) :name(_name) {
cout << "cat类构造" << endl;
};
~cat()
{
cout << "cat类析构" << endl;
}
void speak()
{
cout << "cat类说话" << endl;
}
};
int main()
{
animal* test = new cat("tom");
test->speak();
delete test;
return 0;
}
/*animal类构造
cat类构造
cat类说话
animal类析构
在其中我们发现并没有cat类的析构,因为我们使用基类指针来释放子类的空间,编译器默认使用基类的析构函数。
所以我们需要在基类的析构函数中加virtual
关键字。
virtual ~animal()
{
cout << "animal类析构" << endl;
}
animal类构造
cat类构造
cat类说话
cat类析构
animal类析构
此时完成了cat类的析构。
纯虚函数
在多态中,通常父类中虚函数的实现是毫无意义的,主要都是调用子类重写的内容。
因此可以将虚函数改为纯虚函数。语法:
virtual 返回值类型 函数名 (参数列表) =0
当类中有了纯虚函数,这个类也称为抽象类。
抽象类无法实例化对象,子类必须重写抽象类中的纯虚函数,否则也属于抽象类。
在菱形继承中使用虚基类,构造函数顺序也为基类到子类。但基类构造函数只会调用一次。