I want to write a String class . And you want to use the index to access the item in my String . So I write two member functions, one for the element in the String , and the other - to set the element in Line . Check out the following code:
#include <iostream>
#include <algorithm>
using namespace std;
class String {
public:
String();
String(const char *s);
char &operator[] (int index);
char operator[] (int index) const;
private:
char *arr;
int len;
};
String::String() {
arr = new char[1];
arr[0] = '\0';
len = 0;
}
String::String(const char *s) {
len = strlen(s);
arr = new char[len + 1];
std::copy(s, s + len + 1, arr);
}
char& String::operator[](int index)
{
cout << "mutator []" << endl;
if (index > len || index < 0)
throw std::out_of_range("Index out of range");
return arr[index];
}
char String::operator[](int index) const
{
cout << "accessor []" << endl;
if (index > len || index < 0)
throw std::out_of_range("Index out of range");
return arr[index];
}
int main()
{
String s1 = "abc";
s1[1] = 'b';
String s2 = "efg";
s2[1] = s1[2];
char a = s1[2];
cout << s2[1] << endl;
}
when i run this code. All exits mutator; This bothers me a lot;
source
share