나는이 다음과 같이, operator[]
를 오버로드하는 클래스를 선언하는 다음 코드를C++에서 인덱스 연산자를 오버로드하는 방법은 무엇입니까?
#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[]
의 구현에있어 문제점이 있습니까?
귀하의 Bitset에 대해 연산자 <<를 원하십니까? http://stackoverflow.com/questions/476272/how-to-properly-overload-the-operator-for-an-ostream, http://www.tutorialspoint.com/cplusplus/input_output_operators_overloading.htm – ChuckCottrill