C++接口(抽象类)
接口描述了类的行为和功能,而不需要完成类的特定实现。
C++接口时使用抽象类来实现的,抽象类与数据抽象互补混淆,数据抽象是一个吧实现细节与相关数据分离开的概念。
如果类中至少有一个函数被声明为纯虚函数,则这个类就是抽象类。纯虚函数是通过在声明中使用 "= 0" 来指定的,如下所示:
calss Box{
public:virtual double getvolume() = 0;
private:double l;double h;double b;}
设计抽象类的目的,是为了给其它类提供一个可以继承的适当的基类。抽象类不能被用于实例化对象,他只能作为接口被使用。
所以,如果一个抽象类的子类需要被实例化,则必须实现每一个纯虚函数。
来个例子:
#include<iostream>using namespace std;class Shape{
public:virtual int getArea() = 0;void setwidth(int w){width = w;}void serheight(int h){height = h;}
protected:int width;int height;};class Rectangle : public Shape{
public:int getArea(){return width*height;}
};class Triangle : public Shape{
public:int getArea(){return width*height/2;}
};int main(){Rectangle R;Triangle T;R.serheight(10);R.setwidth(10);cout << R.getArea()<<endl;T.serheight(10);T.setwidth(50);cout << T.getArea()<<endl;return 0;
}