[] overload

F

fox

Hi
I've two classes

class node {
....
node operator[](int idx);
}

and
class grid {
.....
node operator[](int idx);
}

but when i do :
grid *one=new grid();
cout << grid[1][1]
it uses operator [] for grid class, (which returns a node )
and doesn't use an overloaded one for the returned node value;
Is there a way to force him ?
or do i do sth wrong ?

Cheers
 
J

Jeff Schwab

fox said:
Hi
I've two classes

class node {
...
node operator[](int idx);
}

and
class grid {
....
node operator[](int idx);
}

but when i do :
grid *one=new grid();
cout << grid[1][1]
it uses operator [] for grid class, (which returns a node )
and doesn't use an overloaded one for the returned node value;
Is there a way to force him ?
or do i do sth wrong ?

How do you know it's wrong? Did you overload operator << (
std::eek:stream&, node const& )? Is indexing a node really supposed to
give another node?

Please post a small program to show the problem. Someone here probably
can show you what has gone wrong, but it is very difficult to tell from
the pseudocode.

-Jeff
 
D

Dan Cernat

fox said:
Hi
I've two classes

class node {
...
node operator[](int idx);
}

and
class grid {
....
node operator[](int idx);
}

but when i do :
grid *one=new grid();
cout << grid[1][1]
^^^^^^^^^^^^^^^^^^^^^^^^^^ that could not possibly compile
if you meant cout << one[1][1];
then you have some problems here:
1. you allocated only 1 grid element so one[1] is past the array boundaries.
it should have been one[0][1]

2. one is a pointer and when someone does one[n] it actually gets *(one + n)

so what you should have done is:

grid myGrid;
// put here code to fill the collection of nodes
// then do:

cout << grid[1][1];

assuming everything else is working
it uses operator [] for grid class, (which returns a node )
and doesn't use an overloaded one for the returned node value;
Is there a way to force him ?
or do i do sth wrong ?

Cheers

Dan
 
M

Martijn Lievaart

Hi
I've two classes

class node {
...
node operator[](int idx);
}

and
class grid {
....
node operator[](int idx);
}

but when i do :
grid *one=new grid();
cout << grid[1][1]

cout << (*grid)[1][1];

You want to act on the contents of the pointer, not the pointer itself.

HTH,
M4
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,051
Latest member
CarleyMcCr

Latest Threads

Top