如何在c ++中重载accessor和mutator operator []

syd*_*dgm 4 c++ operator-keyword

我想写一个String类.并希望使用下标来访问我的String中的元素.所以,我编写了两个成员函数,一个用于获取String中的元素,另一个用于在String中设置元素.请看下面的代码;

#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
}
Run Code Online (Sandbox Code Playgroud)

当我运行此代码时.它的输出都是mutator; 这让我很困惑;

Gui*_*cot 8

让我们从编译器的角度来看这个案例.我给你这个代码:

String s2;

/* things */ s1[2] /* things */
Run Code Online (Sandbox Code Playgroud)

你选择什么功能?存取者或变异者?由于s2不是const对象,让我们采用非const版本!

这就是为什么你的代码总是打印的原因mutator,编译器不会根据你对结果的处理来选择调用哪个函数.你是否打电话给char分配操作员.

你的const版本不应该返回一个副本,而是一个const引用:

char& operator[](size_t index);
const char& operator[](size_t index) const;
Run Code Online (Sandbox Code Playgroud)

如果尝试写入const字符串,则会收到编译错误而不是未分配的值.


Nat*_*ica 7

char operator[] (int index) const;只有当你有一个时才会被调用const String.如果我们将您main()改为:

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

它会ouptut:

accessor []
Run Code Online (Sandbox Code Playgroud)

Live Example