繁体   English   中英

在c ++中“未在此范围内声明”

[英]“was not declared in this scope” in c++

这是我的头文件

#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

这是my.cpp文件

#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;
}

当我想尝试添加功能时,在我的.cpp文件中,它在添加功能的while循环条件下给了我一个错误。 它说“未在此范围内声明头”。 但是我在.h文件中声明了。 我看不出有什么问题。

您应该使用解析范围运算符,就像您对构造函数和析构函数所做的一样。

因此,您可以在源文件中执行以下操作:

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

然后,当然要在您的类的头文件中声明该函数。

问题很可能是循环包含。 您可能拥有Node.h其中包括LinkedList.h ,反之亦然。 这导致(本质上)一个悖论:如果两个类定义都需要另一个,那么在任何给定的编译单元中首先定义哪个?

实际上,您包含Node.h ,然后尝试再次包含LinkedList.h (请注意, #include字面意思是将“此处复制粘贴此文件”到编译器),但是此时LinkedList_H已被定义(因为这就是您来自),则包含无效。 因此,现在您位于Node.h的中间,但没有LinkedList先前定义,并收到“未声明”错误。

解决的办法是去掉#include Node.hLinkedList.h并与预先声明替换它,因为LinkedList的头定义并不需要知道的东西比“类更多的Node存在的”(因为它仅使用指针)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM