14.5 Static Member Functions
The
member variable stack_count is defined as private.
This means that nothing outside the class can access it. You want to
know how many stacks are defined, so you need a function to get the
value of stack_count. A first cut might be:
class stack {
static int stack_count; // Number of stacks currently in use
// ... member variables
public:
// Not quite right
int get_count( ) {
return (stack_count);
}
// ... other member functions
};
This works, but you need a stack type variable to
access this function.
{
stack temp_stack; // Stack for getting the count
std::cout << "Current count " << temp_stack.get_count( ) << '\n';
}
Because get_count doesn't use any
nonstatic data from stack, it can be made a
static member function:
class stack {
static int stack_count; // Number of stacks currently in use
// ... member variables
public:
// Right
static int get_count( ) {
return (stack_count);
}
// ... other member functions
};
You can now access the static member function get_count
much like you access the static member variable
stack_count:
std::cout << "The number of active stacks is " <<
stack::get_count( ) << '\n';
Static member functions are very limited. They can't
access nonstatic member variables or functions in the class. They can
access static member data, static member functions, and functions and
data outside the class.
|