我有以下代码,它声明了一个重载的类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];
}
};
但是,当我尝试在此代码中使用它时:
#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;
}
我收到此错误:
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[]
?