c++ - 如何在 C++ 中同时重载 = 和 [] 运算符

标签 c++ operator-overloading operator-keyword

在这里,我想通过重载 [] 和 = 运算符来摆脱插入函数。 通过重载 [] 运算符,我成功返回了我想要插入值的所需位置的地址。

#include<iostream>
using namespace std;

#define const maxSize = 30;

class ARRAY
{
private:
    int *ar;
    int end;
public:
    ARRAY()
    {
        ar = new int[40];
        end = -1;
    }

    void insert(int value)
    {
        end += 1;
        ar[end] = value;
    }

    void insert(int value, int index)
    {
        if (index<30 && index >-1)
        {
            int tempEnd = end;
            for (int i = end; i >= index; --i)
            {
                ar[tempEnd + 1] = ar[tempEnd];
                tempEnd -= 1;
            }
            end += 1;
            ar[index] = value;

        }
        else
            cout << "\nOVERFLOW";
    }

    void remove(int index)
    {
        if (index >= 0 && index <= end)
        {
            for (int i = index; i < end; ++i){

                ar[i] = ar[i + 1];
            }
            end -= 1;
            //do something
        }
        else
            cout << "\nNothing gonna happens";
    }

    void display()
    {
        for (int i = 0; i <=end; ++i)
            cout << "\n" << ar[i];
    }

    int* operator[](int at)
    {
        if (at < 40){
            end++;
            return (&ar[at]);

        }
    }

    //Here I want to do = operator overloading, How can I do this?
};

int main()
{
    ARRAY arr;
    arr.insert(1);
    arr.insert(2);
    arr.insert(3);
    arr.insert(4);
    arr.insert(5);
    arr[5] = 10;
    arr.display();
    return 0;
}

最佳答案

您可以通过更改operator[] 的返回类型来实现理想的行为:

int& operator[](int at)

在您的原始代码中,它返回指向数组元素的指针,即使更改,也不会对数组中存储的值做任何事情。使用您的原始代码,您可以编写如下内容来更改元素的值:

*(arr[5]) = 10;

这看起来不明显。

如果返回引用而不是指针,则可以直接更改它引用的值。

关于c++ - 如何在 C++ 中同时重载 = 和 [] 运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41893032/

相关文章:

prolog - 在 Prolog 中重新定义 AND 运算符

C++动态绑定(bind)问题

c++ - QQmlApplicationEngine 和 WindowFlags

c++ - "sizeof new int;"是未定义的行为吗?

c# - 运算符重载 - 为什么静态解析?

c++ - 级联流插入运算符不起作用

objective-c - NSStrings 之前的 '@' 实际上是重载运算符吗?

c++ - 传递给 LogonUser() 的密码不正确,但 Active Directory 帐户未按预期锁定

c++ - "error: expected unqualified-id before ' float ' "用于 operator[] 重载

python - Python 中的运算符优先级 -PEMDAS