// 30限制数组越界 // 该函数有一个参数即数组的下载length, 下标值length会传递到函数体中进行判断,假如下标超过数组的长度,那么返回数组长度-1,也就是最后一个可见字符,假如不超过数组长度,那么返回该下标的数组元素 /*#include <iostream> using namespace std; class String { public: String(); //默认的构造函数 String(const char*const ch); //构造带值的string int getlen()const { return len;} //读取长度 const char *getstr()const{ return str;} //读取字符串 //这里是可以修改的 char &operator[](int length); private: int len; char *str; }; //创建一个空的str变量 String::String() { len = 0; str = new char[1]; str[0] = '\0'; }; String::String(const char*const ch) { cout<<"带一个参数的构造函数"<<endl; len = strlen(ch); str = new char[len+1]; for(int i=0; i<len; i++){ str[i] = ch[i]; } str[len] = '\0'; }; char & String::operator[](int length) { if(length > len){ return str[len-1]; //返回可见字符的值 }else{ return str[length]; } }; int main() { String str; cout<<str.getstr()<<endl; cout<<"str:"<<str.getlen()<<endl; String s1("hello word"); //cout<<s1.getlen()<<endl; cout<<s1.getstr()<<endl; cout<<"s1:"<<s1.getlen()<<endl; char*temp = "help me"; String s3(temp); cout<<s3.getstr()<<endl; cout<<"s3:"<<s3.getlen()<<endl; //越界的值 cout<<"越界的值"<<endl; cin>>s3[999]; cout<<s3.getstr()<<endl; cout<<"s3:"<<s3.getlen()<<endl; cout<<"s3[999]:"<<s3[999]<<endl; return 0; }*/