By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
431,965 Members | 2,043 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 431,965 IT Pros & Developers. It's quick & easy.

operator[] does not work

P: 2
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:

Expand|Select|Wrap|Line Numbers
  1. T& operator[](int i)
  2.     {
  3.         ToFirst();
  4.         for(int j=0;j<i;j++)
  5.         {
  6.             StepForward();
  7.         }
  8.         return Act->value;
  9.     }
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:
Expand|Select|Wrap|Line Numbers
  1. int main()
  2. {
  3.     Lista<int> *tmp;
  4.     int b[]={56,2,87,11,8,34,56,1,9,31,5};
  5.     for(int i=0;i<11;i++)
  6.     {
  7.         tmp->InsertLast(b[i]);
  8.     } <- filling my list
  9.  
  10.      cout<<tmp[3]; 
  11. }
Could someone help me in this?
Nov 15 '10 #1
Share this Question
Share on Google+
3 Replies


Banfa
Expert Mod 5K+
P: 8,916
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

Expand|Select|Wrap|Line Numbers
  1. Lista<int> *tmp = new Lista<int>;
Nov 15 '10 #2

P: 2
Thanks, I fixed it...but I still have problem with it.
I run it, and it says:

v\Adatszerk\lassu_rendezesek\Lassu_rendezesek_hall gatoi\main.cpp||In function `int main()':|
v\Adatszerk\lassu_rendezesek\Lassu_rendezesek_hall gatoi\main.cpp|26|error: no match for 'operator<<' in 'std::cout << *(tmp + 48u)'|

However, I wrote that operator.
Nov 15 '10 #3

Banfa
Expert Mod 5K+
P: 8,916
An error message without the line of code is not very useful.
Nov 17 '10 #4

Post your reply

Sign in to post your reply or Sign up for a free account.