简体   繁体   中英

“was not declared in this scope” in c++

This is my header file

#ifndef LinkedList_H
#define LinkedList_H

#include <iostream>
#include "Node.h"

class LinkedList {
    public:
    int length;
    // pointer to the first element of LinkedList
    Node *head = 0;
    // pointer to the last element of LinkedList
    Node *tail = 0;

    LinkedList();

    ~LinkedList();
};

#endif

and this is my.cpp file

#include "LinkedList.h"

using namespace std;

LinkedList::LinkedList() {
    head=tail;
    this->length=0;
}

LinkedList::~LinkedList() {
    Node *current = head;
    while(current!=NULL){
        Node *temp = current;
        current=current->next;
        delete temp;
    }
}

void add(string _name, float _amount){
    Node *node = new Node(_name, _amount);
    while(head==NULL){ //here, there is an error.
        head=node;
        head->next=tail;
    }
}
int main(){
    LinkedList *list = new LinkedList();
    add("Adam", 7);
    cout<<list->head<<endl;
}

In my .cpp file when I want to try to make an add function, it gives me an error in the while loop condition in add function. It says "head was not declared in this scope". But I declared in .h file. I couldn't see what is wrong.

You should use the resolution scope operator, just like you did for the constructor and the destructor.

So, you in your source file do this:

void LinkedList::add(string _name, float _amount) {

And then, of course, declare that function inside your class, in the header file.

Very likely the problem is circular includes. You probably have Node.h including LinkedList.h and vice-versa. This leads to (essentially) a paradox: If both class definitions require the other, which of the two is defined first in any given compilation unit?

In practice, you include Node.h , which then tries to include LinkedList.h again (note that #include literally means "copy-paste this file here" to the compiler), but at this point LinkedList_H is already defined (because that's where you came from) and the include has no effect. So now you are in the middle of Node.h but with no prior definition of LinkedList and get "not declared" errors.

The solution is to remove the #include Node.h in LinkedList.h and replace it with a forward declaration, since the LinkedList definition in the header doesn't need to know anything more than "the class Node exists" (because it only uses pointers).

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