2013-10-21 2 views
2

나는이 다음과 같이, 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[]의 구현에있어 문제점이 있습니까?

+0

귀하의 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

답변

9

문제는 operator[]의 구현과 관련이 없습니다. 당신이 선언 한 것을 알 a 당신이 컴파일러으로 해석

cout << a[5] << endl; 

을 쓸 때 따라서

BitSet *a; 

,

으로 "배열의 위치에 5시에 요소를 얻을이 다음 출력, a에 의해 지적했다. " 이것은 사용자가 원하는 것이 아니며 BitSetoperator<<이 정의되어 있지 않으므로 오류가 발생합니다. 실제로 발생한 오류는 operator[]이 아닌 BitSet에 약 operator<<입니다. 라인을 변경

봅니다 또는 더 나은 아직, 그냥 포인터 않고 BitSet를 선언

cout << (*a)[5] << endl 

를 읽을 수 있습니다.

희망이 도움이됩니다.

+0

감사합니다. 그리고 jxh에게 첫 번째 질문을 수정 해 주셔서 감사드립니다. – odmenestrator

관련 문제