I'm trying to make a linked list that keeps track of the number of nodes. I created a static variable numNodes
which I increment in the constructor, and which I try to decrement in the deleteNode()
function. However, I get the following error:
quest.cpp: In member function 'void List::deleteNode()':
quest.cpp:25: error: 'struct List::node' has no member named 'numNodes'
This works fine with ordinary variables, but I can't seem to access static ones. I read here that I need to declare the variable with something like
int node::numNodes = 0;
but inserting that into the program gave me other errors.
At line 6:
/tmp//ccrjmtbc.o: In function `List::deleteNode()':
quest.cpp:(.text._ZN4List10deleteNodeEv[List::deleteNode()]+0xe): undefined reference to `List::node::numNodes'
quest.cpp:(.text._ZN4List10deleteNodeEv[List::deleteNode()]+0x17): undefined reference to `List::node::numNodes'
collect2: ld returned 1 exit status
At line 29:
quest.cpp:29: error: type 'List::node' is not derived from type 'List'
At line 32:
quest.cpp: At global scope:
quest.cpp:32: error: 'int List::node::numNodes' is not a static member of 'struct List::node'
The problem seems to be that I don't know how to access the static variable when it's encapuslated in another struct. Am I missing something obvious? Is there a better way to do this? Do I need to declare the variable in a header file? (I'm coming to C++ from Java and am unaccustomed to such things.)
Here's the code (stripped of unnecessary clutter):
#include <cstdlib>
struct List {
struct node {
// static int numNodes; //Didn't work
node() {
static int numNodes = 0;
numNodes++;
}
};
node* nodePtr;
List() {
nodePtr = NULL;
}
void addNode() {
node* n = new node;
nodePtr = n;
}
void deleteNode() {
nodePtr->numNodes--;
delete nodePtr;
}
// int node::numNodes = 0; //Didn't work
};
//int List::node::numNodes = 0; //Didn't work
int main() {
List MyList;
MyList.addNode();
MyList.deleteNode();
}