Possible Duplicate:
Can inner classes access private variables?
Inner class accessing outer class
I have some simple classes nested so they can interact with a variable without extra inputs, yet my compiler gives me an error. How would I allow for them to interact without using &time as function input or having the variable &time inside of the Vect class?
I tried using the same logic where you can have data accessed that is just in the code, at the same place as function prototypes, but is instead wrapped in a class. This works fine for anything I’ve used except other classes. Can anyone explain why?
I have marked the places that use the problematic time variable with comment lines like the one before the define.
/*********/
#define MAX_POLY 3
class Container
{
public:
Container(void);
~Container(void);
float time;/*********/
class Vect
{
float P[MAX_POLY],iT;
public:
Vect(void){iT = 0.0f;P = {0,0,0};}
~Vect(void);
float GetPoly(int n){return P[n];}
float Render(void)
{
float t = time - iT;/*********/
float temp[2] = {0,0};
for(int n=0;n<MAX_POLY;n++)
{
temp[0] = P[n];
for(int m=0;m<n;m++)
temp[0] *= t;
temp[1] += temp[0];
}
return temp[1];
}
void SetPoly(int n,float f)
{
float t = time-iT;/*********/
P[0] = P[2]*t*t + P[1]*t + P[0];
P[1] = 2*P[2]*t + P[1];
//P[2] = P[2];
P[n] = f;
iT = time;/*********/
}
}X;
};
int main()
{
Container Shell;
Shell.X.SetPoly(0,5);
Shell.X.SetPoly(1,10);
Shell.X.SetPoly(2,-1);
for(int n=0;n<10;n++)
{
Shell.time = (float)n;
cout << n << " " << Shell.X.Render() << endl;
}
system("pause");
return 0;
}
The reason you get an error (I managed to figure it out even though you didn’t post the actual error, please do that in the future), is that you actually don’t have an instance of the
Containerclass inside the functions of theVectclass. You should probably think about the design here, but to solve it quickly (and “dirty”) you could add a function which sets aContainerinstance in the sub-class:Edit: A better way is to set a reference to the parent object (thanks to juanchopanza for the idea) using the constructors:
I still think it’s kind of a dirty solution (but not as dirty as my first), and that you should think about changing the design instead.