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):
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.
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.
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?