-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path12.9 ArraySubscriptOperator_MyString.cpp
More file actions
112 lines (93 loc) · 2.27 KB
/
12.9 ArraySubscriptOperator_MyString.cpp
File metadata and controls
112 lines (93 loc) · 2.27 KB
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
#include <iostream>
#include <string>
#include <string.h>
using namespace std;
class MyString
{
private:
char* Buffer;
// private default constructor
MyString() {}
public:
// constructor
MyString(const char* InitialInput)
{
if(InitialInput != NULL)
{
Buffer = new char [strlen(InitialInput) + 1];
strcpy(Buffer, InitialInput);
}
else
Buffer = NULL;
}
MyString operator + (const char* stringIn)
{
string strBuf(Buffer);
strBuf += stringIn;
MyString ret(strBuf.c_str());
return ret;
}
// Copy constructor
MyString(const MyString& CopySource)
{
if(CopySource.Buffer != NULL)
{
// ensure deep copy by first allocating own buffer
Buffer = new char [strlen(CopySource.Buffer) + 1];
// copy from the source into local buffer
strcpy(Buffer, CopySource.Buffer);
}
else
Buffer = NULL;
}
// Copy assignment operator
MyString& operator= (const MyString& CopySource)
{
if ((this != &CopySource) && (CopySource.Buffer != NULL))
{
if (Buffer != NULL)
delete[] Buffer;
// ensure deep copy by first allocating own buffer
Buffer = new char [strlen(CopySource.Buffer) + 1];
// copy from the source into local buffer
strcpy(Buffer, CopySource.Buffer);
}
return *this;
}
const char& operator[] (int Index) const
{
if (Index < GetLength())
return Buffer[Index];
}
// Destructor
~MyString()
{
if (Buffer != NULL)
delete [] Buffer;
}
int GetLength() const
{
return strlen(Buffer);
}
operator const char*()
{
return Buffer;
}
};
int main()
{
cout << "Type a statement: ";
string strInput;
getline(cin, strInput);
MyString youSaid(strInput.c_str());
cout << "Using operator[] for displaying your input: " << endl;
for (int index = 0; index < youSaid.GetLength(); ++index)
cout << youSaid[index] << " ";
cout << endl;
cout << "Enter index 0 - " << youSaid.GetLength() - 1 << ": ";
int index = 0;
cin >> index;
cout << "Input character at zero-based position: " << index;
cout << " is: " << youSaid[index] << endl;
return 0;
}