-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdemo20.cpp
52 lines (42 loc) · 895 Bytes
/
demo20.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#include <iostream>
#include <cstring>
#include <string>
using namespace std;
class String
{
public:
String(char const *chars = "");
char& operator [](size_t index) throw(string);
char operator [](size_t index) const throw(string);
void print()
{ cout << ptrChars << endl; }
private:
char *ptrChars;
static string errorMessage;
};
string String::errorMessage("Subscript out of range");
String::String(char const *chars)
{
chars = chars ? chars : "";
ptrChars = new char[strlen(chars) + 1];
strcpy(ptrChars, chars);
}
char& String::operator [](size_t index) throw(string)
{
if(index >= strlen(ptrChars))
throw errorMessage;
return ptrChars[index];
}
char String::operator[](size_t index) const throw(string)
{
if(index >= strlen(ptrChars))
throw errorMessage;
return ptrChars[index];
}
int main()
{
String s("Hello");
s.print();
cout << s[0] << endl;
return 0;
}