考虑长度和数组指针
#include <string.h>
#include <iostream>
#include <string>
using std::cout;
using std::endl;
using std::string;
class CharArr {
public:
CharArr(int size)
:_len(size)
,_pstr(new char[_len]){
}
~CharArr() {
delete[]_pstr;
}
char &operator[](const int index) {
static char ch = '\0';
if (index >= 0 && index <= _len)
return _pstr[index];
else
cout << "下标越界" << endl;
return ch;
}
private:
int _len;
char * _pstr;
};
int main() {
char * text = "hello world";
int len = strlen(text);
CharArr cha(len);
for (int i = 0; i < len; ++i)
{
cha[i]=text[i];
}
for (int i = 0; i < len; i++)
{
cout << cha[i];
}
cout << "\n";
system("pause");
return 0;
}