虚函数我们一般叫做重写,他是一个抽象的类,他与重载不同。重写我们可以在父类的子类当中进行重写函数功能,不需要和重载一样在同意类中
虚函数在函数类型前加一个virtual,例如:virtual void myprint();//这是虚函数
如果子类中全部进行了重写,我们就可以把它变成纯虚函数,例如:virtual void myprint()=0;//这是纯虚函数。
注意:如果子类中并没有全部进行重写,那么就不能使用纯虚函数不然就报错,一旦写成了纯虚函数的形式,那么我们就不可以实例化自己,也就是new 父类。
下面还有两个后缀可以添加:
1、override 后缀可以强制要求检查函数是重载
2、final 后缀可以终止函数的重载,这个类不会在被继承
接下来,我们用代码来了解虚函数怎么进行基本的实现,大家可以自己CV然后去体会以下虚函数的基本实现(我这里写成了纯虚函数的形式),只要在父类中自己定义一下就是虚函数了。
Father.h
#ifndef FATHER_H
#define FATHER_H
#include <iostream>
using namespace std;
class Father
{
public:
Father(int x);
~Father();
int getX();
void setX(int x);
//=0则为纯虚函数;去掉=0就为虚函数,需要在对应的cpp文件中进行定义功能
//纯虚函数一定要在所有子类中进行重载
virtual void myprint() = 0;
protected:
int x;
};
#endif
Father.cpp
#include "Father.h"
Father::Father(int x)
{
this->x = x;
}
Father::~Father()
{
}
int Father::getX()
{
return this->x;
}
void Father::setX(int x)
{
this->x = x;
}
Child.h
#ifndef CHILD_H
#define CHILD_H
#include <iostream>
#include "Father.h"
using namespace std;
class Child :public Father
{
public:
Child(int x);
~Child();
void myprint();
};
#endif
Child.cpp
#include "Child.h"
using namespace std;
Child::Child(int x) :Father(x)
{
}
Child::~Child()
{
}
void Child::myprint()
{
std::cout << "Child子类myprint" << std::endl;
}
otherChild.h
#ifndef OTHERCHILD_H
#define OTHERCHILD_H
#include "Father.h"
#include <iostream>
using namespace std;
class otherChild :public Father
{
public:
otherChild(int x);
~otherChild();
void myprint();
};
#endif
otherChild.cpp
#include "otherChild.h"
otherChild::otherChild(int x) :Father(x)
{
}
otherChild::~otherChild()
{
}
void otherChild::myprint()
{
std::cout << "otherChild子类myprint" << std::endl;
}
main.cpp
#include <iostream>
#include "Father.h"
#include "Child.h"
#include "otherChild.h"
using namespace std;
int main()
{
//"="左边为静态绑定,发生在编译期,编译的时候就确认了当前的这个pchild的类类型;
//"="右边为动态绑定,因为它发生在运行期间,运行以后执行到该代码才会创建空间并赋值;
//父类指针变量 实例化 子类空间
//默认情况 无条件使用父类的数据和函数
//但要用子类独有,要将变量强转子类的指针调用
Father* arr[2] = { 0 };
Father* pchild1 = new Child(100);
Father* pchild2 = new otherChild(50);
//纯虚函数不可以实例化自己,即不能new自己,只能被用来继承使用,所以下面一行代码错误
//Father* pr = new Father(20);
arr[0] = pchild1;
arr[1] = pchild2;
for (int i = 0; i < 2; i++)
{
cout << "x=" << arr[i]->getX() << endl;
arr[i]->myprint();
/*if (i == 0)
{
((Child*)arr[i])->myPrint();
}
else
{
((otherChild*)arr[i])->myprint();
}*/
}
return 0;
}
运行结果如下所示:
如果有不懂的地方可以 进行私信
如果有讲的不正确的地方,可以帮忙指正。
麻烦大家动动发财的小手给博主一个关注吧