-
Class Pointers
Hi im having a little problem understanding how class pointers work. Ill explain as best i can what i dont understand...
My problem:
Im trying to do a simple graph like data structure, and am having a few problems understanding how to reference the pointers and use them, also if im using them correctly.
The class A should be able to point to 6 neighbours of class A, each of these neighbours in turn have 6 neighbours and so on.
I have a class A like so
Code:
class A
{
public:
A();
~A();
A *one, *two, *three, *four, *five, *six;
};
In A how do i reference the one two etc? Im trying something like below but am having problems.
Code:
#include <iostream>
#include "A.h"
using namespace std;
int main(int argc, char *argv[])
{
A a,b;
// a's first neighbour points to b's four neighbour
a.one = b;
b.four = a;
return 0;
}
How do i get the pointer from a.one to point to object b? Am i using the correct notation? Sorry im new to pointers...!
Also have i defined the class A correctly for the problem im doing?
Sorry if this is a little vague!!!
Thanks
-
a and b are not pointers, they are objects. To assign their addresses to pointers you need to use the address-of operator:
Code:
a.one = &b;
b.four = &a;
>Also have i defined the class A correctly for the problem im doing?
You'll have fun with six links per object, but I don't see a problem with the declaration you have.
-
ah i see, thanks.
so object 'a' s one pointer refers object 'b' s four pointer?
Code:
a.one = &b;
b.four = &a;
-
>so object 'a' s one pointer refers object 'b' s four pointer?
Object a's one pointer refers to object b and object b's four pointer refers to a:
Code:
~ ~
~ b ~
~ a
~ ~ ~
~ ~
This is what you want if you want two adjacent vertices in a graph structure representing six sided cells where the cells are defined as
At least, that's what I'm assuming your graph looks like from the information you've given. :)
-
yes thats exactly the sort of lattice style structure !
so am i going about this the correct way?
i was thinking of a 2D array of cells to store these in, to help with working out the correct neighbour of each
-
>i was thinking of a 2D array of cells to store these in
I was thinking more of an undirected linked graph than an array. It's less awkward. :)
-
>I was thinking more of an undirected linked graph than an array. It's less awkward.
What the heck is an 'undirected linked graph'?
-
hm, is that much more difficult to do? im new with C++ (as u may have guessed !)
could you explain it a little more?
-
>What the heck is an 'undirected linked graph'?
More or less: http://www.nist.gov/dads/HTML/undirectgraf.html
I specified 'linked' to avoid confusion with an array based implementation, I was thinking pointer based. ;)
>is that much more difficult to do?
Well, graphs are a pain no matter what implementation you go with. I just find the linked implementations to be more flexible and easier to work with than array based implementations.