与运算符[]一起使用类

1 c++ class operator-overloading

我正在尝试实现一个“整数”类,希望它像内置类型一样工作int。但我有一个问题:我不能在运营商使用这个类[]int见下面我的代码:

#include <iostream>
using namespace std;

class Integer
{
    private:
        int Value;

    public:
        Integer(int x = 0)
        {
            Value = x;
        }

        void SetValue(int x)
        {
            Value = x;
        }

        int GetValue()
        {
            return Value;
        }

        Integer& operator [] (Integer X);
};

Integer& Integer::operator [] (Integer X)
{
    // Code
}

int main()
{
    Integer X[10];
    Integer I(5);
    int i = 5;

    for(int i=0; i<10; ++i)
        X[i].SetValue(i+1);

    cout << X[i].GetValue() << endl;    // It still work
    cout << X[I].GetValue() << endl;    // Doesn't work

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

有什么办法(不包括强制转换运算符)使运算符[]理解我的Integer类型int呢?

rob*_*oke 5

您正在考虑这种错误方法。您不需要在自己的类上重载[]运算符,实际上您需要将类转换为int,这可以通过重载强制转换运算符来实现。

class Integer
{
public:
  operator int () const { return Value; }
};
Run Code Online (Sandbox Code Playgroud)