C++繼承多型實現介面內容封裝例子
阿新 • • 發佈:2018-12-15
封裝(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);