繁体   English   中英

错误:未在此范围内声明“对象”(C ++)

[英]Error: 'object' was not declared in this scope (C++)

我正在尝试编写Node对象的链接列表,其中每个Node包含:字符串data和指针next 为了管理列表(例如:添加/删除节点),我有Node对象: headcurrtemp 我正在尝试找出将新数据添加到列表时如何将每个节点链接到上一个节点,但是这样做很麻烦。 当我尝试将新节点n链接到curr节点的next指针时,在Node.cpp中发生了错误。

LinkedList.cpp:

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

using namespace std;

LinkedList::LinkedList(value_type setData) {
    head.setData(setData);
    cout << head.getData() << endl;
}

void LinkedList::addNode(value_type addData) {
    Node n;
    n.setData(addData);

    if (head.getData() != "") {
        curr = head;
        while(curr.getNext() != NULL) {
            //Still writing this..
        }
        curr.setNext(n); //Is this correct?
    }
    else {
        head = n;
    }
}

LinkedList.h:

#ifndef LINKEDLIST_H
#define LINKEDLIST_H
#include "Node.h"

class LinkedList {
    public:
        typedef std::string value_type;

        LinkedList();
        LinkedList(value_type setData);
        void addNode(value_type addData);

    private:
        Node head;
        Node curr;
        Node temp;

};

#endif

Node.cpp:

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

using namespace std;

Node::Node() {
    data = "";
    next = NULL;
}

void Node::setData(value_type setData) {
    data = setData;
}

string Node::getData() { 
    return data;
}

void setNext(Node n) {
    next = n; //'next' was not declared in this scope error.
              //Does this assignment statement even work in this scenario?
}

Node * Node::getNext() {
    return next;
}

Node.h:

#ifndef NODE_H
#define NODE_H

class Node {
    private:    
        typedef std::string value_type;

        value_type data;
        Node* next;

    public:
        Node();
        void setData(value_type setData);
        value_type getData();
        void setNext(Node n);
        Node * getNext();
};

#endif

谢谢大家的任何帮助。

你有这行:

void setNext(Node n) {

您可能想要这样:

void Node::setNext(Node n) {

函数void setNext(Node n); class Node声明。 因此,在Node.cpp ,必须使用void Node::setNext(Node n);定义函数void Node::setNext(Node n); 符号::将显示函数的范围。

暂无
暂无

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

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