c++ 编写接口--相关知识 .docx
c++编写接口
在C++中,接口的概念通常通过抽象基类(AbstractBaseClass)来实现。抽象基类包含纯虚函数(PureVirtualFunctions),这些函数在基类中不实现,而由派生类(DerivedClasses)来实现。通过这种方式,抽象基类充当了接口的角色,定义了派生类必须实现的一组函数。
以下是一个简单的C++接口示例,展示了如何定义一个抽象基类以及如何实现该接口的派生类:
cpp代码
#includeiostream
#includestring
//定义一个抽象基类作为接口
classIShape{
public:
//纯虚函数,定义了接口
virtualvoiddraw()const=0;
virtualdoublearea()const=0;
virtual~IShape(){}//虚析构函数,确保正确析构派生类对象
};
//派生类实现接口
classCircle:publicIShape{
private:
doubleradius;
public:
Circle(doubler):radius(r){}
//实现接口中的纯虚函数
voiddraw()constoverride{
std::coutDrawingaCirclestd::endl;
}
doublearea()constoverride{
return3.14159265358979323846*radius*radius;
}
};
classRectangle:publicIShape{
private:
doublewidth,height;
public:
Rectangle(doublew,doubleh):width(w),height(h){}
//实现接口中的纯虚函数
voiddraw()constoverride{
std::coutDrawingaRectanglestd::endl;
}
doublearea()constoverride{
returnwidth*height;
}
};
intmain(){
//使用接口指针来操作对象
IShape*shape1=newCircle(5.0);
IShape*shape2=newRectangle(4.0,6.0);
shape1-draw();
std::coutArea:shape1-area()std::endl;
shape2-draw();
std::coutArea:shape2-area()std::endl;
//释放内存
deleteshape1;
deleteshape2;
return0;
}
在这个示例中:
IShape?是一个抽象基类,它定义了两个纯虚函数?draw()?和?area(),这两个函数构成了接口。
Circle?和?Rectangle?是从?IShape?派生的具体类,它们实现了?IShape?接口中的纯虚函数。
在?main()?函数中,我们使用?IShape?指针来操作?Circle?和?Rectangle?对象,这展示了多态性的使用。
通过这种方式,C++实现了接口的概念,允许我们定义一组函数,这些函数在不同的派生类中有不同的实现。