『C++』Temp_2018_12_26

 

  1 #include <iostream>
  2 #include <string>
  3 #include <array>
  4 using namespace std;
  5 
  6 class Object{
  7 public:
  8     virtual void ToString(){
  9         cout<<"Object"<<endl;
 10     }
 11 
 12 public:
 13     virtual int GetPtrLength(){
 14         return sizeof(this);
 15     }
 16 };
 17 
 18 class Test : public Object{
 19 public:
 20     void ToString(){
 21         cout<<"Test"<<endl;
 22     }
 23 };
 24 
 25 class Ptr{
 26 public:
 27     char Bytes[100];
 28 };
 29 
 30 class Int32{
 31 public:
 32     int m_Value;
 33 public:
 34     int GetPtrLength(){
 35         return sizeof(Int32);
 36     }
 37 };
 38 
 39 
 40 template <class T>
 41 class List{
 42 public:
 43     List() {         m_Count=0;         m_Array = new char*[100];     }
 44     ~List(){         if(m_Array!=NULL) {  delete[] m_Array;  cout<< "释放数组指针"<<endl; } 
 45     }
 46 
 47 private:
 48     int m_Count;
 49     char** m_Array;
 50 
 51 public:
 52     void Add(T* item){
 53         ((Object**)m_Array)[m_Count]=(Object*)item;
 54         m_Count++;
 55     }
 56     Object* operator[](int i)
 57     {
 58         if(i >= m_Count)
 59             throw "索引超过最大值";
 60         return ((Object**)m_Array)[i];
 61     }
 62 
 63 };
 64 
 65 
 66 
 67 
 68 
 69 
 70 
 71 
 72 
 73 
 74 
 75 int main(){
 76     try{
 77         ////初始化一个 指针数组
 78         //Object** aaaa =NULL;
 79         //aaaa = new Object*[1000];
 80         //aaaa[0]=new Object();
 81 
 82 
 83         //cout<< sizeof(Ptr)<<endl;
 84         //cout<<*(new int(1000000))<<endl;
 85 
 86         //char bytes[20];
 87         //int* v0 = (bytes[0]);
 88         //bytes[0] = *(new int(1000000));
 89         //bytes[4] = *(new int(2000000));
 90         //for(int i=0;i<20;i++)
 91         //    cout<< bytes[i];
 92         //cout<<endl;
 93 
 94         //cin.get();
 95         //return  0;
 96 
 97 
 98 
 99 
100 
101 
102 
103 
104         List<Object> list;
105         list.Add(new Object());
106         list.Add(new Test());
107         auto ptr = list[1];
108         ptr->ToString();   //Test
109         //delete list;
110 
111 
112         List<int> list2;
113         list2.Add(new int(100));
114         list2.Add(new int(200));
115         auto ptr2 = list2[1];
116         ptr2->ToString();  //崩溃
117 
118 
119 
120 
121 
122     }catch(char* str){
123         cout<< str << endl;
124     }catch(...){
125         cout<<"未知异常"<<endl;
126     }
127 
128     cin.get();
129     return 0;
130 }

 

执行结果

1 Test
2 程序崩溃

 

posted @ 2018-12-26 17:09  redc  阅读(189)  评论(0编辑  收藏  举报