Accessing variables in a structure

Hi,

I have defined a structure that has six variables in it: let us say that the structure is named PhaseState and the variables are x, y, z, xd, yd, and zd. Now, say I initialize two members/objects of the structure, state[0] and state[1], and I want to do some arithmetic manipulation with the variables of the members, e.g., I want to find the radial distance of the two particles (i.e. sqrt(x*x+y*y+z*z)); however, this results in the bulky code:
sqrt(state[0].x*state[0].x + state[0].y*state[0].y + ....).

Is there a way to say that the variables that will be called in a certain area will only be those of a certain member? In other words, I want to be able to do something like this (kind of like using namespace std):

"using state[0]" { double d0= sqrt(x*x+y*y+z*z); }
"using state[1]" { double d1= sqrt(x*x+y*y+z*z); }

In each bracket, the variables called are those for the respective member.

Can this be done?

Thanks.
C++ does not have a "with" clause like pascal.

The best you can do is eliminate one of them:

1
2
3
4
5
6
// for example:
struct Foo {
   int x, y, z;
   double calc( const Foo& rhs ) const
   {   return sqrt( x * rhs.x + y * rhs.y + z * rhs.z ); }
};

This is exactly what member functions are for. Instead of using a struct, use a class:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class PhaseState
{
public:
  // contrary to what some people might say, having public member
  //  vars is perfectly acceptable in situations like these.
  double x, y, z, dx, dy, dz;

  // and member functions for support
  double RadialDistance()
  {
    return sqrt(x*x+y*y+z*z);
  }
};


//---------------  now instead of doing this:
d0 = state[0].x*state[0].x + /*...etc*/

//---------------  you do this:
d0 = state[0].RadialDistance();
Thanks guys -- both of those methods make sense. I would definitely have used a class except for the fact that I am trying to work with someone else's code and I didn't want to change the structure to a class, but I definitely see the advantages of using a class (in that it allows you to define member functions).

I guess I'll just have to write it all out so that I don't change the existing structure.

Thanks for your help!
structs and classes are absolutely identical in functionality/support except that the default access for structs is public while for classes is private.

Read: you can leave it a struct and implement the member functions with no problems.

(Unless you are using a REALLY old compiler).
oh alright, i got it. i had read in the cplusplus tutorial that only classes allowed for member functions, but i guess maybe the tutorial hasn't been updated?

thanks for your help!
Topic archived. No new replies allowed.