如何在C++中重载索引运算符?

odm*_*tor 2 c++ operator-overloading

我有以下代码声明一个重载的类operator[],如下所示:

#include <iostream>
#include <vector>

using namespace std;

class BitSet
{
private:
    int size;
public:
    vector<int> set;
    int &operator [] (int index) {
        return set[index];
    }
    BitSet(int nsize = 0)
    {
        cout << "BitSet creating..." << endl;
        size = nsize;
        initSet(size);
    }
    void initSet(int nsize)
    {
        for (int i = 0; i < nsize; i++)
        {
            set.push_back(0);
        }
    }
    void setValue(int key, int value)
    {
        set[key] = value;
    }
    int getValue(int key, int value)
    {
        return set[key];
    }

};
Run Code Online (Sandbox Code Playgroud)

但是,当我尝试在此代码中使用它时:

#include <iostream>
#include <stdio.h>
#include "BitSet.h"

using namespace std;

int main()
{
    BitSet *a;
    cout << "Hello world!" << endl;
    a = new BitSet(10);
    a->setValue(5, 42);
    cout << endl << a[5] << endl; // error here
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我收到此错误:

main.cpp|15|??????: no match for «operator<<» in «std::cout.std::basic_ostream<_CharT, _Traits>::operator<< [with _CharT = char, _Traits = std::char_traits<char>, std::basic_ostream<_CharT, _Traits>::__ostream_type = std::basic_ostream<char>](std::endl [with _CharT = char, _Traits = std::char_traits<char>]) << *(a + 200u)»|

我的实施有operator[]什么问题?

tem*_*def 9

该问题与您的实施无关operator[].请注意,您已声明a

BitSet *a;
Run Code Online (Sandbox Code Playgroud)

因此,当你写

cout << a[5] << endl;
Run Code Online (Sandbox Code Playgroud)

编译器将其解释为"在指向的数组中的位置5处获取元素a,然后输出它".这不是你想要的,它会导致错误,因为BitSet没有定义operator<<.(请注意,你得到的实际误差大约operator<<BitSet,而不是约operator[]).

尝试更改要阅读的行

cout << (*a)[5] << endl
Run Code Online (Sandbox Code Playgroud)

或者,更好的是,只需声明它BitSet而不是指针.

希望这可以帮助!