I have the following code which declares a class that overloads operator[], as shown here:
#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];
}
};
However, when I try to use it in this code:
#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;
}
I get this error:
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)»|
What's wrong with my implementation of operator[]?
The issue has nothing to do with your implementation of operator[]. Notice that you've declared a as
BitSet *a;
Therefore, when you write
cout << a[5] << endl;
the compiler interprets this as "get element at position five in the array pointed at by a, then output it." This isn't what you want, and it causes an error because BitSet doesn't define an operator<<. (Notice that the actual error you're getting is about operator<< in BitSet rather than about operator[]).
Try changing the line to read
cout << (*a)[5] << endl
Or, better yet, just declare the BitSet without making it a pointer.
Hope this helps!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With