大家好~我用out_of_range()做异常处理,设定的输出语句总是不对,请帮帮我~谢谢
这是头文件
//array.h
#ifndef ARRAY_H
#define ARRAY_H
#include <stdexcept> //for the exception classes
template <typename T> class Array {
private:
T* elements; //array of type T
size_t size; //number of elements in the array
public:
explicit Array(size_t arraySize); //constructor
Array(const Array& theArray); //copy constructor
~Array(); //destructor
T& operator[](size_t index); //subscript operator
const T& operator[](size_t index) const; //subscript operator
Array& operator=(const Array& rhs); //assignment operator
};
//constructor
template <typename T> //this is a template with parameter T
Array<T>::Array(size_t arraySize) : size(arraySize) {
elements=new T[size];
}
//copy constructor
template <typename T>
Array<T>::Array(const Array& theArray) {
size=theArray.size;
elements=new T[size];
for(int i=0; i<size; i++)
elements[i]=theArray.elements[i];
}
//destructor
template <typename T>
Array<T>::~Array() {
delete[] elements;
}
//subscript operator
template <typename T>
T& Array<T>::operator[](size_t index) {
if(index<0 || index>=size)
throw std::out_of_range(index<0?"Negative index":"Index too large"); /打算,索引值小于0输出第一句,否则输出第二句
return elements[index];
}
//assignment operator
template <typename T>
Array<T>& Array<T>::operator=(const Array& rhs) {
if(&rhs==this)
return *this;
if(elements)
delete[] elements;
size=rhs.size;
elements=new T[rhs.size];
for(int i=0; i<size; i++)
elements[i]=rhs.elements[i];
}
#endif
这是主程序
//main.cpp
#include "array.h"
#include <iostream>
#include <iomanip>
using std::cout;
using std::endl;
int main () {
const int doubleCount=50;
Array<double> values(doubleCount); //class constructor instance created
try {
for(int i=0; i<doubleCount; i++)
values[i]=i+1; //member function instance created
cout<<endl<<"Sums of pairs of elements: ";
int lines=0;
for(int i=doubleCount-1; i>=0; i--)
cout<<(lines++%5==0?"\n":" ")<<std::setw(5)
<<values[i]+values[i-1]; //这里i=0时,i-1就小于0了,应该引发错误处理机制的第一条语句
}
catch(const std::out_of_range& ex) {
cout<<endl<<"out_of_range exception object caught! "<<ex.what();
}
cout<<endl;
system("pause");
return 0;
}
运行结果是
Sums of pairs of elements:
99 97 95 93 91
89 87 85 83 81
79 77 75 73 71
69 67 65 63 61
59 57 55 53 51
49 47 45 43 41
39 37 35 33 31
29 27 25 23 21
19 17 15 13 11
9 7 5 3
out_of_range exception object caught! Index too large
怎么输出的是错误处理机制中的第二条语句呢,应该是“Negative index”才对啊。。
[此贴子已经被作者于2007-4-17 20:58:43编辑过]