Home > Mobile >  Private member c problems [duplicate]
Private member c problems [duplicate]

Time:09-23

I've run into an error that I don't know how to fix. My program does not compile because it outputs "declared private here". Not sure how to fix this, looking for feedback in order to improve my skills! Thanks in advance.

I've only included the areas where I am experiencing issues.

class List
{
    public:
        List() { first = NULL; } // constructor
        List(const List& source); // copy constructor
        ~List(); // destructor
        
        int length() const; // returns the length of the list that invokes it
        bool present(const int& target) const;
        void insert(const int& entry); // inserts the item n into the invoking list, in the appropriate position
        void merge(List, List); // merges the two lists l1 and l2 into the invoking list
        void makeEmpty(); // re-initializes an exisiting list to be empty

        friend ostream& operator<<(ostream& out, List& c); // friend function for class

    private:
        struct Node
        {
            int data;
            Node *next;
        };
        Node *first;

        Node* get_node(const int& entry, Node* link); // allocates, initializes, and returns the address of a new node
        
};


ostream& operator << (ostream& out, const List& c)
{
    List::Node *cursor;

    out << " ";

    for (cursor = c.first; cursor != NULL && cursor -> next != NULL; cursor = cursor -> next)
        out << cursor -> data << ", ";

    if (cursor != NULL)
        out << cursor -> data;
        out << " ";

    return out;
}

Here is what my compiler outputs

301Project3test.cpp: In function 'std::ostream& operator<<(std::ostream&, const List&)':

301Project3test.cpp:166:11: error: 'struct List::Node' is private within this context

     List::Node *cursor;

301Project3test.cpp:30:16: note: declared private here

         struct Node

301Project3test.cpp:170:21: error: 'List::Node* List::first' is private within this context

     for (cursor = c.first; cursor != NULL && cursor -> next != NULL; cursor = cursor -> next)

301Project3test.cpp:35:15: note: declared private here

         Node *first;

CodePudding user response:

List declares its friend operator<< as taking a List&, but you are implementing the operator as taking a const List& instead, so you are actually implementing a different operator, not the friend operator that has access to the private List::Node type.

  •  Tags:  
  • c
  • Related