C风格字符串的越界异常处理
#include <iostream>
#include <cstring>
using namespace std;
class MyStr{
char str[200];
public:
void set(string str);
char at(unsigned int a);
};
void MyStr::set(string str){
strcpy(this->str,str.c_str());
}
char MyStr::at(unsigned int a){
if(strlen(str)<=a){
throw int(2);
}
return str[a];
}
int main()
{
MyStr s1;
int n=0;
s1.set("longthim");
cin >> n;
try {
cout << s1.at(n) << endl;
} catch (int) {
cout << "越界访问" << endl;
return -1;
}
return 0;
}
#include <iostream>
using namespace std;
class Figure{
int n;
public:
Figure():n(0){}
void MyGetChar();
};
class Alpha{
char ch;
public:
Alpha():ch('a'){}
void MyGetChar();
};
void Figure::MyGetChar(){
if(n<=9){
cout << n ;
n++;
}
}
void Alpha::MyGetChar(){
if(ch<='z'){
cout << ch;
ch++;
}
}
int main()
{
Figure f1;
Alpha a1;
for(int i=0;i<26;i++){
f1.MyGetChar();
a1.MyGetChar();
}
return 0;
}