Krazy Dev
Krazy Dev

Reputation: 182

Unable to use Linked List in Main.cpp

I'm new to C++ and am coming from a C# background. I'm trying to practice with linked list.

The issue I am having is that I am trying to use the following linked list I created:

class Board {
typedef struct BoardList{
        Board b_data;
        Node *next;
    }* boardPtr;

    boardPtr head;
    boardPtr current;
    boardPtr temp;

}

Now I'm trying to "instantiate" it in my main method but I'm not sure how to accomplish this. This is what I researched and found online but it is still not working-

int main(){

BoardList* first = NULL; //first element will be added after a board object is added to the list that's why i left this as null

}

But I keep getting a "Can't resolve type BoardList" error. I'm using CLion for my IDE.

Upvotes: 0

Views: 48

Answers (2)

Problem 1:

Boardlist is an inner type, so you need to prefix it with Board::

Problem 2

Boardlist is defined privately, when it should be public.

Code with corrections:

class Board {
public:
    typedef struct BoardList{
        Board b_data;
        Node *next;
    }* boardPtr;

    boardPtr head;
    boardPtr current;
    boardPtr temp;

}

int main(){

Board::BoardList* first = NULL; 

}

Upvotes: 0

Coral Kashri
Coral Kashri

Reputation: 3506

You don't have to use typedef keyword do declare new struct in c++. To declare BoardList pointer type, use typedef keyword. Try this code:

class Board {
    struct BoardList{
        Board b_data;
        Node* next;
    };
    using BoardList* boardPtr;

    boardPtr head;
    boardPtr current;
    boardPtr temp;
}

For the main section- BoardList is availible only in the class Board, because it defines inside a private section of this class. If you want to use this struct outside the class Board you have some options:

Declare BoardList in public section of the class Board

class Board {
public:
    struct BoardList{
        Board b_data;
        BoardList* next;
    };

private:
    ....
};

int main() {
    Board::BoardList* first = NULL;
    return 0;
}

Declare BoardList above the class Board

class Board; // Pay attention! Forward declaration is required here!

struct BoardList{
    Board *b_data; // Pay attention! You have to use pointer in this case because it is defined above the class. You can declare it under the class as I will show in the next section. 
    BoardList *next;
};

class Board {
    typedef BoardList* boardPtr;

    boardPtr head;
    boardPtr current;
    boardPtr temp;

};

int main(){

    BoardList* first = NULL;

    return 0;
}

Declare BoardList under the class Board

struct BoardList; // Pay attention! Forward declaration is required here!

class Board {
    typedef BoardList* boardPtr;

    boardPtr head;
    boardPtr current;
    boardPtr temp;

};

struct BoardList{
    Board *b_data;
    BoardList *next;
};

int main(){

    BoardList* first = NULL;

    return 0;
}

Upvotes: 1

Related Questions