How to overload access operator and mutator [] in C ++

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);
}

//mutator operator[] ---> used to change data members;
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];
}
//Accessor operator[]---> used to read data members
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';  //---> should use mutator operator
    String s2 = "efg";
    s2[1] = s1[2]; //---> should use both accessor and mutator operator
    char a = s1[2]; //---> should use accessor operator
    cout << s2[1] << endl; //---> should use accessor operator
}

when i run this code. All exits mutator; This bothers me a lot;

+4
source share
2 answers

Look at this case from the point of view of the compiler. I present to you this code:

String s2;

/* things */ s1[2] /* things */

? ? s2 const, !

mutator, , , , . char .

const , const:

char& operator[](size_t index);
const char& operator[](size_t index) const;

, , const.

+6

char operator[] (int index) const; const String. main() :

int main()
{
    const String s1 = "abc";
    char a = s1[2]; //---> should use accessor operator
}

:

accessor []

+7

Source: https://habr.com/ru/post/1616568/


All Articles