職能類模型2

//vec.h
//包含處理venctor數組操作的一組函數模板
//ventry 2008-5-29

#include <vector>

//--------------------------------------------------------------------------------
//元素壓入ventor數組
template<typename T>
inline int vec_PushBack( std::vector<T>& t_vec, const T& t )
{
 t_vec.push_back(t);
 return 1;
}

//--------------------------------------------------------------------------------
//跟據元素值刪除第一個符合條件的元素
template<typename T>
int vec_DelObj( std::vector<T>& t_vec, const T& t )
{
 for (int i=0; i<t_vec.size(); i++)
 {
  if(t_vec[i]==t)
  {
   t_vec.erase(t_vec.begin()+i);
   return i;
  }
 }
 return -1;
}

//--------------------------------------------------------------------------------
//根據下標刪除符合條件的元素
template<typename T>
inline int vec_DelObj( std::vector<T>& t_vec, int i )
{
 if(i<0 || i> t_vec.size()-1 ) return -1;
 delete t_vec[i];
 return 1;
}

//--------------------------------------------------------------------------------
//清除vector數組中所有元素
template<typename T>
int vec_Clear( std::vector<T>& t_vec )
{
 int res = t_vec.size();
 for (int i=t_vec.size()-1; i>=0; i--)
 {
  delete t_vec[i];
 }
 return res;
}
//--------------------------------------------------------------------------------

 

//main.cpp-----------------------------

 

#include <iostream>
#include "vec.h"
#include <string>
using namespace std;
//--------------------------------------------------------------------------------
class A
{//有個前提,它的所有子類都是單根繼承或者它作爲父類被繼承時排在第一位,並且默認它和它的子類指針值是相同的
public:
 A(int data){ m_data = data; vec_PushBack(instanc_vec,this);}
 virtual ~A(){ vec_DelObj(instanc_vec, this); }
 const static vector<A*>& GetObjVec(){ return instanc_vec; }
 static int DelObj(int i){  return vec_DelObj( instanc_vec,i ); }
 static int Clear(){  return vec_Clear(instanc_vec); }
 virtual int put()=0;
 int m_data;
 
protected:
 static vector<A*> instanc_vec;
 
};

//--------------------------------------------------------------------------------
class B:public A
{
public:
 B(int data):A(data){}
 //virtual ~B(){ vec_DelObj(A::instanc_vec, (A*)this);}
 int put(){ return 0; }

};


//--------------------------------------------------------------------------------
void pnt()
{
 cout<<"---------------------------------------------"<<endl;
 for (int i=0;i<A::GetObjVec().size();i++)
 {
  cout<<A::GetObjVec()[i]->m_data<<endl;
 }
}

//----------------------------------------------------------------------------------
vector<A*> A::instanc_vec;
//----------------------------------------------------------------------------------

int main(void)
{
 A *pa = new B(123);
 B *pb = new B(546);

 pnt();
 //delete pa;
 A::DelObj(1);
 pnt();
 A::DelObj(0);
  pnt();
 return 0;

 

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章