简体   繁体   中英

C++ Access struct in sourcefile

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. 

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 .

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.

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 .

  • include the .h file in your .cc file
  • refer to structure as List::ListNode as it is a nested type
  • don't have to write struct ListNode* startPtr; just List::ListNode* startPtr;
  • insert semicolon after class List definition in .h file

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, eg you should write:

List::ListNode* startPtr;

instead of

struct ListNode* startPtr;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM