在本篇文章中,我们主要介绍虚函数抽象类的内容,自我感觉有个不错的建议和大家分享下
1、在基类中不能给出有意义的虚函数定义,这时可以把它说明成纯虚函数,把它的定义留给派生类来做 2、定义纯虚函数: class 类名{ virtual 返回值类型 函数名(参数表) = 0; }; 3、纯虚函数不需要实现
#include <iostream> #include<vector> using namespace std;
class Shape { public: virtual void Draw()=0; virtual ~Shape()//如果不是纯虚函数,则派生类析构函数不能执行,会形成内存泄漏问题
{
cout<<"~Shape().........."<<endl; } }; class Circle:public Shape { public: void Draw() { cout<<"Circle::Draw().........."<<endl; } ~Circle(){ cout<<"~Circle().........."<<endl; } }; class Square:public Shape { public: void Draw() { cout<<"Square::Draw().........."<<endl; } ~Square() { cout<<"Square::~Square().........."<<endl; } }; class Retangle:public Shape { public: void Draw() { cout<<"Square::Retangle().........."<<endl; } ~Retangle() { cout<<"Retangle::~Retangle().........."<<endl; } protected: private: };
void DrawAllShape(vector<Shape*> v) { vector<Shape*>::const_iterator it;
for (it=v.begin();it!=v.end();++it) { Shape* s=(*it); s->Draw(); } }
void DeleteAllShape(vector<Shape*> v) { vector<Shape*>::const_iterator it;
for (it=v.begin();it!=v.end();++it) { delete (*it); } } // class ShapeFactory { public:
static Shape* CreateFactory(const string& name){ Shape *ps=0; if (name.compare("Circle")) { ps=new Circle; } else if(name.compare("Square")) { ps=new Square; }else if (name.compare("Retangle")) { ps=new Retangle; } return ps; } protected: private: };
int main() { // Shape s; error ,抽象类不能实例化 //Circle c; //c.Draw();
Shape* ps;
vector<Shape*> ve; /* ps=new Circle;
ve.push_back(ps);
ps=new Square;
ve.push_back(ps);
ps=new Retangle;
ve.push_back(ps);*/
ps=ShapeFactory::CreateFactory("Circle"); ve.push_back(ps); ps=ShapeFactory::CreateFactory("Square"); ve.push_back(ps); ps=ShapeFactory::CreateFactory("Retangle"); ve.push_back(ps); DrawAllShape(ve); DeleteAllShape(ve); return 0; }
//1、抽象类只能作为基类来应用 //2、不能声明为抽象类的对象 //3、构造函数不能是虚函数,析构函数可所以虚函数 //4、抽象类不能用于直接创建对象实例 //5、可应用指向抽象类的指针支持运行时多态性 //6、派生类中必须实现抽象类中的纯虚函数,否则它仍将被看作一个抽象类
文章结束给大家分享下程序员的一些笑话语录: 某程序员对书法十分感兴趣,退休后决定在这方面有所建树。花重金购买了上等的文房四宝。一日突生雅兴,一番磨墨拟纸,并点上了上好的檀香,颇有王羲之风 范,又具颜真卿气势,定神片刻,泼墨挥毫,郑重地写下一行字:hello world.
--------------------------------- 原创文章 By 虚函数和抽象类 ---------------------------------