这算不算是 编译器的bug
下面的问题好奇怪 大家看看是为什么
#ifndef MyLinearList_
#define MyLinearList_
#include <iostream.h>
#include <stdlib.h>
#include "xcept.h"
const int NUM = 3 + 2;
template<class T>
class MyLinearList
{
public:
MyLinearList(int MaxSizeValue = 100);
~MyLinearList();
MyLinearList<T>& Find(int i, int k, T &x);
MyLinearList<T>& Insert(int i, int k,const T &x);
MyLinearList<T>& Delete(int i, int k, T &x);
private:
int First[NUM];
int Last[NUM];
T *element;
int MaxSize;
};
template<class T>
MyLinearList<T>::MyLinearList(int MaxSizeValue )
{
MaxSize = MaxSizeValue;
/// element = (T *)malloc(sizeof(T) * MaxSize);
/*如果这条语句放在这里 执行完成后element 地址0x00431cd0,但是在调用Insert()时
element 地址都会变为 0x0000084;导致内存访问错误.*/
First[0] = Last[0] = -1;
First[4] = Last[4] = MaxSize - 1;
///为每个表分配各自的空间
int eachsize = MaxSize / 3;
for(int i = 1; i <= NUM; i ++)
{
First[i] = Last[i] = (i - 1) * eachsize;
}
element = (T *)malloc(sizeof(T) * MaxSize); ////放在这里 则没有问题.
}
template<class T>
MyLinearList<T>::~MyLinearList()
{
delete [] element;
}
template<class T>
MyLinearList<T>& MyLinearList<T>::Insert(int i, int k, const T &x)
{
// if(i < 0 || i > NUM)
// OutOfBounds();
if(0 < k && k <= (Last[i] - First[i]) + 1)
{
for(int j = Last[i] - 1; j > First[i] + k; j --)
{
element[j] = element[j - 1] ;
}
element[First[i] + k - 1] = x;
Last[i] ++;
}
// OutOfBounds();
return *this;
}
#endif
/////////////main() 函数
#include <iostream.h>
#include "MyLinearList.h"
int main()
{
MyLinearList<int> L(100);
L.Insert(1, 1, 2); /////L.element[0] = x;
L.Insert(1, 2, 3);
return 0;
}