Re: Simple List Access by Index
serkan.kabak@gmail.com wrote:
I've created these simple Node and List classes, but I want to be able
to do something like this: L[0] = 5; L[1] = 10; L[2] = 20; etc.... How
would I need to overload my operator= in the List class?
Actually, my first guess would be that you need to overload operator[], but
let's look at the code...
class Node
{
friend ostream& operator<<(ostream& out, const Node& N)
{
cout << N.data << " --> ";
}
Note: you don't have to make this function a friend, there is a public API
to retrieve the value. However, you need to learn about const and non-const
memberfunctions, because as it is now, you can't use getData() on N above,
because getData() is declared as a non-const memberfunction.
int data;
Node* next;
public:
Node() {}
Node(int d, Node* n)
{
data=d; next=n;
}
~Node() {}
void setData(int d) { data=d; }
int getData() { return data; }
void printData() { cout << data << endl; }
Note: both getData() and printData() should be conste. Further, printData()
in my eyes doesn't belong there at all, because it is easily achievable in
a more explicit and universal way with the free operator<< or with a
getData() call.
int operator=(const Node& N) { return N.data; }
Hmmm, interesting. Normally, operator= is supposed to assign something. Now
this one only returns the value of the right-hand side of the assignment.
What would be normal is this:
Node& operator=(Node const& rhs)
{
// note: not assigning 'next'!
data = rhs.data;
return *this;
}
class List
{
Node N;
Node* top;
int num_;
Your list contains a Node, a pointer to a Node and a signed number. If it's
a dynamic container, what is the single 'N' for?
List(int num): num_(num) //create list
{
top = new Node[num];
}
~List() //destroy list
{
delete[] top;
}
Node& operator[](int i) {return top[i]; }
Okay, one thing I can say now: you are never using Node::next, so you are
not actually coding a linked list here (as the name otherwise suggests) but
rather a dynamic array class. If you remove the 'next' pointer, all that
the Node class will contain is a single 'int', so in fact you could easily
replace the whole type with 'int', apart from a few function calls perhaps.
void operator=(Node& N)
{
//code to be placed here...
}
If you code this, it should assign to the list and not to a single object of
the list. That is what operator= in class Node would be for. However, what
is the meaning of assigning a 'Node' to a 'List'?
void print()
{
List L(num_);
for(int i=0; i<num_; i++)
{
cout << L[i];
}
}
Note:
* This function should be const, see above explanations and also the FAQ.
* Instead of printing the list this is invoked on, it creates a list with
the same number of arguments and prints each of its elements.
* You could also overload operator<< for 'List'.
Uli
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]