Connell Gauld wrote:
Hi,
I'm using VC++.
I have a class called exClass defined in exClass.h
exClass has a static variable, declared like this in the public section.
static int exStaticVar;
Below the class definition I have initialised (right word?) it like this
int exClass::nextFree;
No,
class exClass { static int staticVar; ... } // is reffered as definition
(header file)
int exClass::staticVar; // is reffered as declaration or instantiation
(implementation file)
int exClass::staticVar=0;// declared and initialised at the same time!
To your problem in the code:
exClass * otherClass::doFunction(args)
{
...
if(condition)
{
// The line below works fine.
someFunction(exClass.exStaticVar);
// The line below does not.
exClass.exStaticVar++;
}
...
}
If you use exClass.*, you mean a instance of class exClass with the name
exClass, i.e. like:
int nameOfInstance; // int is the type and nameOfInstance the name of an
instance of type int;
exClass exClass; // the first exClass is the type and the second
would be the instance.
So, don't mix up instance names and class names. If you want to use the
static variable of a class, you have to refere to it via its namespace:
AnyClass::staticVariableName.
In this way you can access the variable anywhere in your code.
If you use it in class-function, you can leave the AnyClass:: referring
scheme.
So in your code just use staticVar (since you use it in the implementation
part of your class).
You can also access static vars of an class via an instance:
exClass instanceOfExClass;
instanceOfExClass.staticVar =0;
But keep in mind, that it is a static variable and any change of staticVar
is visible to all instances.
Static functions and variables do not need any instance of the class (by the
way).
So use exClass::staticVar of just staticVar in your code.
I do not know your definition of someFunction and why it works in the first
place. But it's strange code anyway.
regards,
Gottfried