您当前的位置: 首页 > 学无止境 > 心得笔记 网站首页心得笔记
第24讲-抽象方法
发布时间:2021-05-18 17:22:49编辑:雪饮阅读()
纯虚函数
純虛函數也被稱爲抽象方法
您可能想要在基类中定义虚函数,以便在派生类中重新定义该函数更好地适用于对象,但是您在基类中又不能对虚函数给出有意义的实现,这个时候就会用到纯虚函数。
對於上篇中所用實例則可以利用抽象方法來改造,如:
#include <iostream>
using namespace std;
class Shape {
protected:
int width, height;
public:
Shape( int a=0, int b=0)
{
width = a;
height = b;
}
//純虛函數
virtual int area() = 0;
};
class Rectangle: public Shape{
public:
Rectangle( int a=0, int b=0):Shape(a, b) { }
int area ()
{
cout << "Rectangle class area :" <<endl;
return (width * height);
}
};
class Triangle: public Shape{
public:
Triangle( int a=0, int b=0):Shape(a, b) { }
int area ()
{
cout << "Triangle class area :" <<endl;
return (width * height / 2);
}
};
// 程序的主函数
int main( )
{
Shape *shape;
Rectangle rec(10,7);
Triangle tri(10,5);
// 存储矩形的地址
shape = &rec;
// 调用矩形的求面积函数 area
shape->area();
// 存储三角形的地址
shape = &tri;
// 调用三角形的求面积函数 area
shape->area();
return 0;
}
則編譯運行結果如:
= 0 告诉编译器,函数没有主体,上面的虚函数是纯虚函数。
关键字词:純虛函數,抽象方法
上一篇:第23讲-虚方法
下一篇:第25讲-运算符重载
相关文章
-
无相关信息