多态的本质:基类和派生类中拥有相同成员函数名,实现不同函数功能
(同名函数在不同类中有不同实现,即不同类中不同功能的函数有相同的函数名)
#include<iostream>
using namespace std;
class Father
{
public:
void display() {
cout << "输出基类函数" << endl;
}
};
class Son :public Father
{
public:
void display() {
cout << "输出派生类函数" << endl;
}
};
int main(void) {
Father* p = new Father();//基类指针 指向基类
p->display();//调用基类函数
p = new Son();//基类指针 指向派生类
p->display();//调用派生类函数
}
输出结果:
输出基类函数
输出基类函数
为了实现多态,使基类函数指针能访问派生类成员函数,C++增加了虚函数virtual,在基类函数声明前加上virtual即可。
使得:基类指针指向基类对象时,就是使用基类成员(成员函数,成员数据),基类指针指向派生类对象,就是使用派生类成员。
#include<iostream>
using namespace std;
class Father
{
public:
virtual void display() {
cout << "输出基类函数" << endl;
}
};
class Son :public Father
{
public:
void display() {
cout << "输出派生类函数" << endl;
}
};
int main(void) {
Father* p = new Father();//基类指针 指向基类
p->display();//调用基类函数
p = new Son();//基类指针 指向派生类
p->display();//调用派生类函数
}
输出结果:
输出基类函数
输出派生类函数