C++純虛函數、抽象類和接口類
1.純虛函數:純虛函數是在基類中聲明的虛函數,它在基類中沒有定義,但要求任何派生類都要定義自己的實作方法。在基類中實作純虛函數的方法是在虛函數原型後加“=0”
例如:
virtual void takeoff() = 0;
2.抽象類:含有純虛函數的類叫做抽象類(抽象類不能執行個體化對象)。
3.接口類:一般隻含有純虛函數的類(故接口類屬于抽象類)。接口類更多的用來表達一種能力或協定。接口類是隻提供方法聲明,而自身不提供方法定義的抽象類。接口類自身不能執行個體化,接口類的方法定義/實作隻能由接口類的子類來完成。
4.執行個體
Flyable.h
//接口類
#ifndef FLYABLE_H
#define FLYABLE_H
class Flyable
{
public:
virtual void takeoff() = 0;
virtual void land() = 0;
};
#endif`
Plane.h
#ifndef PLANE_H
#define PLANE_H
#include "Flyable.h"
#include<string>
#include<iostream>
using namespace std;
class Plane:public Flyable
{
public:
Plane(string code);
virtual~Plane();
virtual void takeoff();
virtual void land();
void printCode();
protected:
string m_strCode;
};
#endif
Plane.cpp
#include"Plane.h"
Plane::Plane(string code)
{
m_strCode = code;
}
Plane::~Plane()
{
}
void Plane:: takeoff()
{
cout << m_strCode << " plane:takeoff\n";
}
void Plane::land()
{
cout << m_strCode << " plane:land\n";
}
void Plane::printCode()
{
cout << "printCode:" << m_strCode << endl;
}
FighterPlane.h
#ifndef FIGHTERPLANE_H
#define FIGHTERPLANE_H
#include"Plane.h"
#include<string>
#include<iostream>
using namespace std;
class FighterPlane:public Plane
{
public:
FighterPlane(string code);
virtual~FighterPlane();
virtual void takeoff();
virtual void land();
};
#endif
FighterPlane.cpp
#include"FighterPlane.h"
FighterPlane::FighterPlane(string name) :Plane(name)
{
}
FighterPlane::~FighterPlane()
{
}
void FighterPlane::takeoff()
{
cout << "fighterplane:takeoff\n";
}
void FighterPlane::land()
{
cout << "fighterplane:land\n";
}
main.cpp
//僅含有純虛函數的類稱為接口類,即類中沒有資料成員,隻有成員函數且成員函數為純虛函數
//接口類更多的用來表達一種能力或協定
#include<iostream>
#include<string>
#include<stdlib.h>
#include"Flyable.h"
#include"Plane.h"
#include"FighterPlane.h"
using namespace std;
void flyMatch(Flyable *f1, Flyable *f2)
{
f1->takeoff();
f1->land();
f2->takeoff();
f2->land();
}
int main(void)
{
Plane p1("001");
Plane p2("002");
p1.printCode();
p2.printCode();
flyMatch(&p1, &p2);
FighterPlane f1("003");
FighterPlane f2("004");
f1.printCode();
f2.printCode();
flyMatch(&f1, &f2);
system("pause");
return 0;
}