//我在写一个用数组描述的线性表时遇到了两个错误,在抛出异常时总是无法实现转换
#include<iostream>
#include<string>
#include<sstream>
using namespace std;
//定义一个异常类
class illegalParameterValue
{
public:
illegalParameterValue() :
message("Illegal parameter value") {}
illegalParameterValue(char* theMessage)
{
message = theMessage;
}
void outputMessage()
{
cout << message << endl;
}
private:
string message;
};
//抽象类linearLIst
template<class T>
class linearList
{
public:
virtual ~linearList() {};
virtual bool empty()const = 0;//当且仅当线性表为空时,返回true
virtual int size()const = 0;//返回线性表的元素个数
virtual T& get(int theIndex)const = 0;//返回索引为theIndex的元素
virtual int indexOf(const T& theElement)const = 0;//返回元素theIndex第一次出席那时的索引
virtual void erase(int theIndex) = 0;//删除索引为theIndex的元素
virtual void insert(int theIndex, const T& theElement) = 0;//把theElement插入线性表中索引为theIndex的位置上
virtual void output(ostream& out)const = 0;//把线性表插入输出流out
};
//变长一维数组
template<class T>
void changeLength1(T*& a, int oldLength, int newLength)
{
if(newLength < 0)
{
throw illegalParameterValue("new length must be >= 0 ");
}
T* temp = new T[newLength];
int number = min(oldLength, newLength);//需要复制的元素个数
copy(a, a + number, temp);
delete[] a; //释放老数组中的内存空间
a = temp;
}
//类arrayList的定义
template<class T>
class arrayList :public linearList<T>
{
public:
arrayList(int initialCapacity = 10);
arrayList(const arrayList<T>&);
~arrayList() { delete[] element; };
bool empty()const
{
return listSize == 0;
}
int size()const
{
return listSize;
}
T& get(int theIndex)const;
int indexOf(const T& theElement)const;
void erase(int theIndex);
void insert(int theIndex, const T& theElement);//常量指针指向的值不可以修改
void output(ostream& out)const;
int capacity()const
{
return arrayLength;
}
protected:
void checkIndex(int theIndex)const;//若索引theIndex无效,则抛出异常
T* element; //存储线性表元素的一维数组
int arrayLength; //一维数组的容量
int listSize; //线性表的元素个数
};
//类arrayList的构造函数
template<class T>
arrayList<T>::arrayList(int initialCapacity)
{
//构造函数
if (initialCapacity < 1)
{
ostringstream s;
s << "Initial capacity = " << initialCapacity << "must be > 0";
throw illegalParameterValue(s.str());
}
arrayLength = initialCapacity;
element = new T[arrayLength];
listSize = 0;
}
template<class T>
arrayList<T>::arrayList(const arrayList<T>& theList)
{
//拷贝构造函数
arrayLength = theList.arrayLength;
listSize = theList.listSize;
element = new T[arrayLength];
copy(theList.element, theList.element + listSize, element);
}
int main()
{
//arrayList实例化
//创建两个容量为100的线性表
linearList<int>* x = new arrayList<int>(100);
system("pause");
return 0;
}
运行结果及报错内容

第一处是在变长一维数组里面的
第二处是在类arrayList构造函数里面的
我的解答思路和尝试过的方法
我把异常类中的有参构造函数中的参数改为 const char* ,但还是有一个报错

但是我是按照数据结构,算法与应用这本书里面的程序写的,不知道为什么会报错