【问题标题】:Error: 'object' was not declared in this scope (C++)错误:未在此范围内声明“对象”(C++)
【发布时间】:2015-09-09 05:08:34
【问题描述】:

我正在尝试编写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

任何帮助将不胜感激,谢谢大家。

【问题讨论】:

  • 在链表中包含当前节点可能不是一个好主意。

标签: c++ list pointers scope


【解决方案1】:

你有这行:

void setNext(Node n) {

你可能想要这个:

void Node::setNext(Node n) {

【讨论】:

  • 啊,是的,解决了,谢谢老兄。你知道我将如何重写next = n; 语句,因为我认为它不正确。
  • next = n; 声明对我来说很好。
【解决方案2】:

函数void setNext(Node n);class Node 中声明。所以在Node.cpp中,你必须用void Node::setNext(Node n);定义函数。符号:: 将显示函数的作用域。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多