首页 > 解决方案 > 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 文件中,当我想尝试创建一个 add 函数时,它在 add 函数的 while 循环条件中给了我一个错误。它说“头没有在这个范围内声明”。但我在 .h 文件中声明。我看不出有什么问题。

标签: c++oop

解决方案


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

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

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

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


推荐阅读