operator[] does not work

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • szidijani
    New Member
    • Nov 2010
    • 2

    operator[] does not work

    Hello!

    I have a homework for tomorrow, and I simply can't solve it.
    I have a list (with template) class, I wrote and it has an operator:

    Code:
    T& operator[](int i)
        {
            ToFirst();
            for(int j=0;j<i;j++)
            {
                StepForward();
            }
            return Act->value;
        }
    For using the elements with indexes.
    And I've got an another class, which puts the elements of an object(template ) in order.

    And when I make a pointer of this classin main, and I try to just write on the console one of the elements...it doesn't work:
    Code:
    int main()
    {
        Lista<int> *tmp;
        int b[]={56,2,87,11,8,34,56,1,9,31,5};
        for(int i=0;i<11;i++)
        {
            tmp->InsertLast(b[i]);
        } <- filling my list
    
         cout<<tmp[3]; 
    }
    Could someone help me in this?
    Last edited by Markus; Nov 16 '10, 01:00 PM. Reason: Added [code] tags, undeleted thread and moved it to /c/answers/
  • Banfa
    Recognized Expert Expert
    • Feb 2006
    • 9067

    #2
    At the point where you say <- filling my list you are not filling your list you are writing to uninitialised data because you never allocate an object for tmp to point to and it is therefore pointing at a random place.

    Try

    Code:
    Lista<int> *tmp = new Lista<int>;

    Comment

    • szidijani
      New Member
      • Nov 2010
      • 2

      #3
      Thanks, I fixed it...but I still have problem with it.
      I run it, and it says:

      v\Adatszerk\las su_rendezesek\L assu_rendezesek _hallgatoi\main .cpp||In function `int main()':|
      v\Adatszerk\las su_rendezesek\L assu_rendezesek _hallgatoi\main .cpp|26|error: no match for 'operator<<' in 'std::cout << *(tmp + 48u)'|

      However, I wrote that operator.

      Comment

      • Banfa
        Recognized Expert Expert
        • Feb 2006
        • 9067

        #4
        An error message without the line of code is not very useful.

        Comment

        Working...