一.写出程序运行结果
1#include <iostream >
using namespace std;
int a[10]={1,2, 3, 4, 5, 6, 7, 8, 9, 10};
int fun( int i);
void main()
{int i ,s=0;
for( i=0;i<=10;i++)
{ try
{ s=s+fun(i);}
catch(int)
{cout<<”数组下标越界!”<<endl;}
}
cout<<"s=”<<s<<endl;
}
int fun( int i)
{if(i>=10)
throw i;
return a[i];
}
数组下标越界!
S=55
2 #include <iostream>
using namespace std;
void f();
class T
{public:
T( )
{cout<<"constructor"<<endl;
try
{throw "exception";}
catch( char*)
{cout<<"exception”<<endl;}
throw "exception";
}
~T( ) {cout<<"destructor";}
};
void main()
{cout<<"main function”<< endl;
try{ f( ); }
catch( char *)
{ cout<<"exception2"<<endl;}
cout<<"main function”<<endl;
}
void f( )
{ T t; }
main function
constructor
exception
exception2
main function
二、程序设计题
1以String类为例,在String类的构造函数中使用new分配内存。如果操作不成功,则用try语句触发一个char类型异常,用catch语句捕获该异常。同时将异常处理机制与其他处理方式对内存分配失败这一异常进行处理对比,体会异常处理机制的优点。
2在1的基础上,重载数组下标操作符[],使之具有判断与处理下标越界功能。
解法一
#include <iostream>
#include <cstring>
using namespace std;
class String{
public:
String(const char*);
String(const String&);
~String();
char operator[](int);
void ShowStr(){cout<<sPtr<<endl;}
private:
char *sPtr;
};
1 #include <iostream> using namespace std; int a[10]={1,2, 3, 4, 5, 6, 7, 8, 9, 10}; int fun( int i); void main() { int i, s=0; for(i=0; i<=10; i++) { // 第十趟不会完整运行 try { s=s+fun(i); } catch(int) { cout<<"数组下标越界!"<<endl; } } cout<<"s="<<s<<endl; } int fun(int i) { if (i>=10) throw i; return a[i]; } 2 #include <iostream> using namespace std; void f(); class T { public: T() { cout<<"constructor"<<endl; // 2 try { throw "exception";} catch( char*) { cout<<"exception"<<endl;} // 3 throw "exception"; } ~T( ) {cout<<"destructor";} // 不被执行 }; void main() { cout<<"main function"<< endl; // 1 try { f( ); } catch( char *) { cout<<"exception2"<<endl;} // 4 cout<<"main function"<<endl; // 5 } void f( ) { T t; } 3 #include <iostream> #include <cstring> using namespace std; class String{ public: String(const char*); String(const String&); ~String(); char operator[](int i); void ShowStr(){cout<<sPtr<<endl;} private: char *sPtr; }; // 构造函数 String::String(const char *s) { sPtr = new char[strlen(s)+1]; if (sPtr == NULL) throw ("Constructor abnormal"); strcpy(sPtr, s); } String::String(const String& copy) { sPtr = new char[strlen(copy.sPtr) + 1]; if (sPtr == NULL) throw ("Copy constructor abnormal"); strcpy(sPtr, copy.sPtr); } String::~String() { delete[] sPtr; } // 重载数组下标操作符 char String::operator [] (int i) { if (i < 0 || i > strlen(sPtr)) throw ("Exception: overflow. "); return sPtr[i]; } int main() { String hi("hello"); try { hi.ShowStr(); printf("hi[0]=%c ", hi[0]); printf("hi[1]=%c ", hi[1]); printf("hi[2]=%c ", hi[2]); printf("hi[3]=%c ", hi[3]); printf("hi[4]=%c ", hi[4]); printf("hi[5]=%c(zero) ", hi[5]); printf("hi[6]=%c ", hi[6]); // error! } catch (char* exception) { cout << exception << endl; } return 0; } /* output: hello hi[0]=h hi[1]=e hi[2]=l hi[3]=l hi[4]=o hi[5]= (zero) Exception: overflow. */