版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/wwwsssZheRen/article/details/84864155
封装(private中的数据都通过Get与Set来访问)可以使代码模块化,继承(:)可以扩展已存在的代码,而多态的目的是为了接口重用(即相同名字的接口可能实现不同的Function功能,因为他们可能可以扩展成一个子类)。多态通过父类指针操作子类对象成员函数。
虚函数:允许被其子类重新定义的成员函数,子类重新定义父类虚函数的做法,可实现成员函数的动态覆盖。
一、以下是一个多态的举例,父类为shape(指形状)里面有形状的面积计算这个功能。
class Shape
{
public:
Shape();
~Shape();
virtual float caculateArea() = 0;
private:
};
又有两个子类去继承这一个父类,分别是圆Circle和矩形Rectangle,子类中有父类的虚函数具体调用方法,但函数名是相同的,都为caculateArea()。
class Circle : public Shape
{
public:
Circle(float input_r){ r = input_r; };
float caculateArea()
{
float area = 3.14 * r * r;
return area;
};
private:
int r;
};
class Rectangle : public Shape
{
public:
Rectangle(float width, float height)
{
rect_width = width;
rect_height = height;
};
float caculateArea()
{
float area = rect_height * rect_width;
return area;
};
private:
float rect_width;
float rect_height;
};
在调用过程中,相同的函数caculateArea()可分别实现不同的调用方法体现多态。
Shape * shape_circle = new Circle(2.0);
float area_circle = shape_circle->caculateArea();
Shape *shape_rectangle = new Rectangle(4.0,3.0);
float area_rect = shape_rectangle->caculateArea();
二、客户需要调用的一些接口函数,如果你用到OPENCV,不能将用到的一些接口给客户。
#include "common.h"
class OCRMODEL
{
public:
static OCRMODEL * Create();
static void Destroy(OCRMODEL * ocrmodel);
virtual bool DoOcr(const ImageU & input_mat, const RecTangle rectan, std::string & output_string, float & reliability) = 0;
virtual bool Load(const char* path_knndata, const char* path_eastmodel) = 0;
virtual ~OCRMODEL() {}
};
具体使用方式,继承自一个类,这时候可以任意写include的东西。
#include "OCRMODEL.h"
#include <opencv2/opencv.hpp>
#include <iostream>
#include <io.h>
#include "GetIndividualNumberFromImg.h"
#include "KnnNumRecognition.h"
#include "functions.h"
using namespace std;
using namespace cv;
class OCRMODELCHILD :public OCRMODEL
{
public:
OCRMODELCHILD();
~OCRMODELCHILD();
bool DoOcr(const ImageU & input_mat, const RecTangle rectan, std::string & output_string, float & reliability);
bool Load(const char* path_knndata, const char* path_eastmodel);
private:
GetIndividualNumberFromImg getelements;
KnnNumRecognition KnnRecog;
};
OCRMODELCHILD::OCRMODELCHILD(){ }
OCRMODELCHILD::~OCRMODELCHILD(){ }
bool OCRMODELCHILD::DoOcr(const ImageU & input_mat, const RecTangle rectan, std::string & output_string, float & reliability){ ... }
bool OCRMODELCHILD::Load(const char* path_knndata, const char* path_eastmodel){...}
OCRMODEL * OCRMODEL::Create()
{
return new OCRMODELCHILD();
}
void OCRMODEL::Destroy(OCRMODEL * ocrmodel)
{
if (ocrmodel) delete ocrmodel;
}
调用
OCRMODEL *ocr_model = OCRMODEL::Create();
ocr_model->Load(path_knndata,path_eastmodel);
bool Decis = ocr_model->DoOcr(src_img, rect_roi, output_string, reliability);
OCRMODEL::Destroy(ocr_model);