抽象基类(abstract base class,ABC)
例子:圆与椭圆。建立一个基类BaseEllipse,建立它的恋歌继承了Ellipse和Circle。
ellipse.h
#ifndef ELLIPSE_H_ #define ELLIPSE_H_ class BaseEllipse { public: virtual double Area() const =0; }; class Ellipse : public BaseEllipse { private: double a, b; public: Ellipse(double a, double b) : a(a), b(b) {} virtual double Area() const; }; class Circle : public BaseEllipse { private: double r; public: Circle(double r) : r(r) { } virtual double Area() const; }; #endif // ELLIPSE_H_
ellipse.cpp
#include "ellipse.h" double Ellipse::Area() const { return 3.14159 * a * b; } double Circle::Area() const { return 3.14159 * r * r; }
测试类
#include <iostream> #include "ellipse.h" int main() { using std::cout; using std::endl; double a = 1.0, b = 2.0, r = 3.0; Ellipse * ellipse = new Ellipse(a, b); cout << ellipse->Area() << endl; Circle * circle = new Circle(r); cout << circle->Area() << endl; return 0; }
输出效果:
6.28318 28.2743