简体   繁体   中英

How does typdef of an undefined struct pointer name work in C++?

Let me explain the question with the help of code.

I have following two files.

cat ah

    typedef struct myIterStruct*   myIter;

    class myIterator;

    class myList
    {
        int mVal;
        myList* mNext;
        friend class myIterator;

        public:

        myList(myList* next, int val) : mVal(val), mNext(next) {}

        ~myList() {}

        void AddTail(int val) {
            myList* newnode = new myList(NULL, val);
            myList* tail = this->GetTail();
            tail->mNext = newnode;
        }   

        myList* GetTail() {
            myList* node = this;
            while (node->mNext)
                node = node->mNext;
            return node;
        }   

        myList* GetNext() { return mNext; }

        int GetVal() { return mVal; }
    };

    class myIterator
    {
        myList*   mList;

        public:

        myIterator(myList* list) : mList(list) {}
        ~myIterator() {}

        int next() {
            int ret = -1; 
            if (mList) {
                ret = mList->GetVal();
                mList = mList->GetNext();
            }
            return ret;
        }   
    };

cat main.cxx

#include <iostream>
#include "a.h"
using namespace std;

myIter createIterator(myList* list)
{
    myIterator *returnitr = new myIterator(list);
    return (myIter) returnitr;
}

int myListGetNextNode(myIter iter)
{
    if (iter == NULL)
        return -1; 
    myIterator* funciter = (myIterator *) iter;
    return funciter->next();
}

int main() 
{

    myList* list = new myList(NULL, 1); 
    list->AddTail(2);
    list->AddTail(3);

    myIter iter = createIterator(list);
    int val = -1; 

    while((val = myListGetNextNode(iter)) != -1) {
        cout << val << '\t';
    }   
    cout << endl;

    return 0;
}

This code is used in a project to implement list and iterator. What I am not able to understand is first line in ah file : "typedef struct myIterStruct *myIter;"

In the code, definition of struct myIterStruct is written nowhere, still this code compiles and works well.

Does the C++ compiler convert the undefined struct pointer to void*? or is this specific to g++ compiler that I am using? Please elaborate.

Thanks.

It is enough to know that myIterStruct is a class or struct. When the compiler sees struct myIterStruct it knows that and can form a pointer to it.

The rule that this must work, indirectly forces the compiler use the same size for all pointers to class/struct.

Some other pointers, particularly void* and char* , might use additional bytes on some unusual systems.

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