如果一个类至少有一个纯虚函数,就称该类为抽象类,目的是用它作为基类去建立派生类。
规定:
1.抽象类中至少包含一个没有定义功能的纯虚函数,因此,抽象类只能作为其他类的基类来使用,不能建立抽象类对象。
2.不允许从具体类(不包含纯虚函数)派生抽象类
3.不能函数参数类型,函数返回类型
4.可以声明指向抽象类的指针或引用,该指针可以指向他的派生类来实现多态
5.关键是定义纯虚函数,只有定义了纯虚函数该类才是抽象类,如果没定义久是具体类。
应用c++多态性,计算三角形,矩形和圆的面积
#include<iostream> using namespace std; class Figure { protected: double x; double y; public: Figure(double i,double j) {x = i;y = j;} void set_dim(double i,double j = 0) {x = i;y = j;} virtual void show_area() = 0;//纯虚函数 };//抽象类 class Triangle : public Figure//三角形 { public: Triangle(double h,double d):Figure(h,d){} void show_area() {cout<<"Triangle with high:"<<x<<" and base:"<<y<<" has an area of:"<<x*0.5*y<<endl;} }; class Square :public Figure//矩形 { public: Square(double a,double b):Figure(a,b){} void show_area() {cout<<"Square with dimension:"<<x<<"*"<<y<<" has an area of: "<<x*y<<endl;} }; class Circle : public Figure//圆 { public: Circle(double r):Figure(r,r){}//虽然两个参数一样但也必须传两次 void show_area() { cout<<"Circle with radius:"<<x<<" has an area of: "<<3.14*x*x<<endl; } }; void fun(Figure &n) { n.show_area(); } int main() { Figure *p;//定义基类指针 Triangle t(10.0,6.0); Square s(10.0,6.0); Circle c(10.0); cout<<"指针"<<endl; p = &t; p->show_area(); p = &s; p->show_area(); p = &c; p->show_area(); cout<<"引用"<<endl; fun(t); fun(s); fun(c); return 0; }
原文地址:http://blog.csdn.net/cherry_ermao/article/details/45746527