Reputation: 11
I've defined my struct
in a .h
file, and I'm trying to access it from a .cc
file. However, I keep getting errors when compiling.
This is in my .h
:
class List
{
public:
struct ListNode
{
string data;
ListNode* next;
};
}
And this is in my .cc
file: (the .h
file is included)
struct ListNode* startPtr;
List::List(void)
{
startPtr = new ListNode;
startPtr = nullptr;
}
When trying to use it like this,
void Print()
{
while (startPtr)
{
cout << startPtr->data << endl;
startPtr = startPtr->next;
}
}
I get errors like
Forward declaration and unauthorized usage of undefined type.
Upvotes: 1
Views: 91
Reputation: 5
Let me rephrase the answer of Kiril Kirov. You have 2 types in your program: - ListNode defined in the scope of the class List - ListNode defined in global scope The 2nd one is defined using forward declaration, without actual description of its content. That's your compiler trying to say to you. To fix the error you need to refer correct ListNode type, when defining startPtr, e.g. you should write:
List::ListNode* startPtr;
instead of
struct ListNode* startPtr;
Upvotes: 0
Reputation: 38163
You must include
the .h
file in your .cc
file AND as ListNode
is defined inside class List
, if you want to access it from outside the class (outside its definition & its methods), you need to specify the scope like this List::ListNode
.
Note, that if class List
is defined inside a specific namespace, for example my_namespace
, if you want to access ListNode
from the global namespace, you need to specify this, too. Like: my_namespace::List::ListNode
.
Upvotes: 3
Reputation: 29724
List::ListNode
as it is a nested typestruct ListNode* startPtr;
just List::ListNode* startPtr;
List
definition in .h fileUpvotes: 0
Reputation: 71959
You made ListNode
a nested type of List
, so you have to refer to it as List::ListNode
. You can leave off the struct
when you declare startPtr
though.
Of course, since List::ListNode
is redundant, you might want to rename it to just Node
.
Upvotes: 0
Reputation: 70929
Your list node class is inner class. It's type is: List::ListNode
not just ListNode
like you use it.
Also as you mention forward declaration(though I don't see any in this code): you will not be able to forward declare an inner class.
Upvotes: 0