c++ - Accessing a member of struct in class, LinkedList Node -
so starting out learning linkedlists c++. know c+ has library them i'm trying focus on linkedlists. exercise saw asks design linked list class 2 fellow member functions , default constructor: add, ismember, , linkedlist() constructor. add together function adds new node front end of list. ismember tests see if list contains node value passed in add.
my issue is, creating listnode *head in struct, seek access in linkedlist constructor set null, throwing me error of "undeclared identifier". if set null in struct gives me same error. error goes away if write "listnode *head = null" in constructor, add together method still going crazy on utilize of "undeclared identifier" head. here's got far:
linkedlist.h:
class linkedlist { protected: struct listnode { double value; listnode *next; listnode(double value1, listnode *next1 = null) { value = value1; next = next1; } listnode *head; }; // public interface public: // class constructor(s) linkedlist(); // methods void add(double x); bool ismember(double x); // private class members private: }; linkedlist.cpp:
#include "stdafx.h" #include "linkedlist.h" // class definition file // class default constructor linkedlist::linkedlist() { head = null; } // class destructor linkedlist::~linkedlist(void) { listnode *nodeptr; while (nodeptr != null) { listnode *garbage = nodeptr; nodeptr = nodeptr->next; delete garbage; } } void linkedlist::add(double x) { listnode *nodeptr, *prevnodeptr; if (head == null || head->value >= x) { head = new listnode(x, head); } else { nodeptr = head->next; while (nodeptr != null && nodeptr->value < x) { prevnodeptr = nodeptr; nodeptr = nodeptr->next; } prevnodeptr->next = new listnode(x, nodeptr); } } bool linkedlist::ismember(double x) { //tbd } any clues why huge help. thanks!
you declare listnode structure, never declare anywhere object has listnode type. when seek access head element within linkedlist method, indeed undeclared identifier, because linkedlist class doesn't have element called head.
if have changed linkedlist declaration that:
class linkedlist { protected: struct listnode { double value; listnode *next; listnode(double value1, listnode *next1 = null) { value = value1; next = next1; } listnode *head = null; } node; // instantiating listnode element part of linkedlist class // public interface public: // class constructor(s) linkedlist(); // methods void add(double x); bool ismember(double x); // private class members private: }; then have called head element in way:
linkedlist::linkedlist() { node.head = null; } c++ class struct linked-list nodes
No comments:
Post a Comment