仅含有纯虚函数的类称为接口类
无数据成员
成员函数都是纯虚函数
Flyable.h
#ifndef FLYABLE_H
#define FLYABLE_H
class Flyable
{
public:
virtual void takeoff() = 0;
virtual void land() = 0;
};
#endif // ! FLYABLE_H
Plane.h
#ifndef PLANE_H
#define PLANE_H
#include <string>
#include "Flyable.h"
using namespace std;
class Plane :public Flyable
{
public:
Plane(string code);
virtual void takeoff();
virtual void land();
void printCode();
private:
string m_strCode;
};
#endif // !PLANE_H
Plane.cpp
#include "Plane.h"
#include <iostream>
using namespace std;
Plane::Plane(string code)
{
m_strCode = code;
}
void Plane::takeoff()
{
cout << "Plane---takeoff" << endl;
}
void Plane::land()
{
cout << "Plane---land" << endl;
}
void Plane::printCode()
{
cout << m_strCode << endl;
}
FighterPlene.h
#ifndef FIGHTERPLANE_H
#define FIGHTERPLANE_H
#include "Plane.h"
#include <string>
using namespace std;
class FighterPlane :public Plane
{
public:
FighterPlane(string code);
virtual void takeoff();
virtual void land();
};
#endif // !FIGHTERPLANE_H
FighterPlane.cpp
#include "FighterPlane.h"
#include "FighterPlane.h"
#include <iostream>
using namespace std;
FighterPlane::FighterPlane(string code) :Plane(code)
{
}
void FighterPlane::takeoff()
{
cout << "FigheterPlane---takeoff" << endl;
}
void FighterPlane::land()
{
cout << "FighterPlane---land" << endl;
}
Demo.cpp
#include "Plane.h"
#include "FighterPlane.h"
void flyMatch(Flyable *f1, Flyable *f2)
{
f1->takeoff();
f1->land();
f2->takeoff();
f2->land();
}
int main(void)
{
Plane p1("001");
FighterPlane p2("002");
p1.printCode();
p2.printCode();
flyMatch(&p1, &p2);
system("pause");
return 0;
}
运行
多继承,父类可以是接口类也可以是普通类
Person.h
#ifndef PLANE_H
#define PLANE_H
#include <string>
#include "Flyable.h"
using namespace std;
class Plane
{
public:
Plane(string code);
void printCode();
private:
string m_strCode;
};
#endif // !PLANE_H
FighterPlane.h
#ifndef FIGHTERPLANE_H
#define FIGHTERPLANE_H
#include "Plane.h"
#include <string>
using namespace std;
class FighterPlane :public Plane,public Flyable
{
public:
FighterPlane(string code);
virtual void takeoff();
virtual void land();
};
#endif // !FIGHTERPLANE_H
Demo.cpp
#include "Plane.h"
#include "FighterPlane.h"
void flyMatch(Plane *f1, Flyable *f2)
{
f1->printCode();
f2->takeoff();
f2->land();
}
int main(void)
{
FighterPlane p1("001");
FighterPlane p2("002");
flyMatch(&p1, &p2);
system("pause");
return 0;
}